Created
June 3, 2012 06:07
-
-
Save editnuki/2862182 to your computer and use it in GitHub Desktop.
乱数作成メソッド
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @author nuki ここではヒットアンドブローのための ランダムな被りのない4桁の数字を生成するクラス作成する。 | |
* | |
*/ | |
public class CreateRandomNumber { | |
// 乱数の桁数を定数として生成 | |
public static final int FINAL_NUMBER = 4; | |
public static void RandomNumber() { | |
// 乱数を生成する | |
// int 型の配列arrという変数名を宣言 | |
int[] arr; | |
// 配列の要素数を指定して配列を生成 | |
arr = new int[FINAL_NUMBER]; | |
// 配列の添字を0から順に乱数を代入する | |
for (int i = 0; i < FINAL_NUMBER; i++) { | |
// Mathクラスのrandomメソッドを用いて0.0〜0.9の乱数を生成し、1を足すことで整数にする。 | |
// 整数なのでdouble型ではなくint型にキャストする | |
arr[i] = (int) (Math.random() * 9) + 1; | |
// ラベル付きbreakで前の添字とかぶっていない場合次の添字の要素を生成する | |
nyaruko: | |
// 添字1〜3は前の数値とかぶっていないかの確認 | |
if (i > 0) { | |
// 1つ前の添字の要素と同じ場合(true)は再度乱数を生成する | |
while (arr[i] == arr[i - 1]) { | |
arr[i] = (int) (Math.random() * 9) + 1; | |
} | |
} else { | |
break nyaruko; | |
} | |
} | |
// 動作確認で配列の中身を添字0から表示させる | |
for (int i = 0; i < FINAL_NUMBER; i++) { | |
System.out.print(arr[i]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment