Created
June 4, 2012 00:07
-
-
Save editnuki/2865525 to your computer and use it in GitHub Desktop.
20120603CreateRandomNumber
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
package jp.ac.ca.data.create; | |
/** | |
* | |
* @author nuki ここではヒットアンドブローのための ランダムな被りのない4桁の数字を生成するクラス作成する。 | |
* | |
*/ | |
public class CreateRandomNumber { | |
/* | |
* 乱数の桁数を定数として宣言 | |
* | |
* 他のクラスから見る必要がないのでアクセス修飾子はprivateに設定 他のメソッドなどで上書きされたくもないのでfinalが適当と判断 | |
* 4桁というのは変わらないので定数で宣言 | |
*/ | |
private static final int ARRAY_SIZE = 4; | |
/* | |
* このメソッドが外のクラスから呼べないと困るのでアクセス修飾子はpublic | |
* インスタンスメソッドではなく、クラスメソッドとして作成したためstaticとしている 戻り値は配列なので配列を指定する | |
* 乱数生成に引数を受け取る必要はないので空引数 | |
* | |
*/ | |
public static int[] randomNumber() { | |
// 乱数を生成する | |
// int 型の配列arrという変数名を宣言 | |
int[] arr; | |
// 配列の要素数を指定して配列を生成 | |
arr = new int[ARRAY_SIZE]; | |
// ラベル付きbreakで前の添字とかぶっていない場合次の添字の要素を生成する | |
// nyaruko: | |
// 配列の添字を0から順に乱数を代入する | |
for (int i = 0; i < ARRAY_SIZE; 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++) { | |
// 31行目で生成した乱数がその前の添字の配列要素と同じでないか確認 | |
if (arr[i] == arr[n]) { | |
// arr[i] = (int) (Math.random() * 9) + 1; | |
// iをデクリメントし28行目のfor文で同じ添字の配列要素をもう一度生成する | |
i--; | |
// for文から抜けて再度チェックを行う。 | |
break;// loop; | |
} | |
} | |
// } else { | |
// continue nyaruko; | |
} | |
} | |
// 動作確認で配列の中身を添字0から表示させる | |
// for (int i = 0; i < FINAL_NUMBER; i++) { | |
// System.out.print(arr[i]); | |
// } | |
return arr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment