『Java入門第1四半期』のRandomクラスと乱数取得事例
/*
* Random:乱数を生成するクラス
*
* 構築方法:
*
public Random():フィードが与えられず、デフォルトのフィードが使用され、現在の時間のミリ秒値での乱数なので、常に変化します
*
public Random(long seed):指定したシードを与える long seedはlongタイプのデータです
* シードが与えられた後、毎回得られる乱数は(同じ)である.再コンパイル実行後のデータは変わりません.
* 種は何なのか、どうやって変わらないのか.例によって説明する.
*/
出力結果:
294 971 958 698 410 921 285 613 598 966 -------------------------- 857 683 744 768 282 613 23 743 763 414
出力結果の再コンパイル:
294 971 958 698 410 921 285 613 598 966 -------------------------- 751 924 654 376 20 95 563 576 43 108
このとき何が種なのか、何が不変なのかと変化の違いは一目瞭然だろう.
また,Randomを用いて1−100を取得する別の方法も完了した.つまり、上のコードは次のとおりです.
* Random:乱数を生成するクラス
*
* 構築方法:
*
public Random():フィードが与えられず、デフォルトのフィードが使用され、現在の時間のミリ秒値での乱数なので、常に変化します
*
public Random(long seed):指定したシードを与える long seedはlongタイプのデータです
* シードが与えられた後、毎回得られる乱数は(同じ)である.再コンパイル実行後のデータは変わりません.
* 種は何なのか、どうやって変わらないのか.例によって説明する.
*/
public class RandomDemo {
public static void main(String[] args) {
//
Random r1 = new Random();//
Random r = new Random(111);//long
// 10 1-100
for (int x = 0; x < 10; x++) {
// int num = r.nextInt();
int num = r.nextInt(100) + 1;
System.out.println(num);
}
System.out.println("--------------------------");
for(int x = 0; x < 10; x++){
int num = r1.nextInt(100) + 1;
System.out.println(num);
}
}
}
出力結果:
294 971 958 698 410 921 285 613 598 966 -------------------------- 857 683 744 768 282 613 23 743 763 414
出力結果の再コンパイル:
294 971 958 698 410 921 285 613 598 966 -------------------------- 751 924 654 376 20 95 563 576 43 108
このとき何が種なのか、何が不変なのかと変化の違いは一目瞭然だろう.
また,Randomを用いて1−100を取得する別の方法も完了した.つまり、上のコードは次のとおりです.
for (int x = 0; x < 10; x++) {
// int num = r.nextInt();
int num = r.nextInt(100) + 1;
System.out.println(num);
}