Created
June 3, 2012 06:27
-
-
Save editnuki/2862229 to your computer and use it in GitHub Desktop.
乱数生成メソッド2
This file contains 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
package data.create; | |
/** | |
* | |
* @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]; | |
// ラベル付きbreakで前の添字とかぶっていない場合次の添字の要素を生成する | |
nyaruko: | |
// 配列の添字を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; | |
// 添字1〜3は前の数値とかぶっていないかの確認 | |
if (i > 0) { | |
loop: | |
// arr[i]の要素をn < i の間の添字の配列要素と被っていないかの確認 | |
for (int n = 0; n < i; n++) { | |
// 22行目で生成した乱数がその前の添字の配列要素と同じでないか確認 | |
// 同じ場合は最生成してloopラベルに戻り再度確認 | |
while (arr[i] == arr[n]) { | |
arr[i] = (int) (Math.random() * 9) + 1; | |
break loop; | |
} | |
} | |
} else { | |
continue 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