ここでは乱数を生成する方法を解説していきます。
乱数の生成の方法
import文
Randomクラスの生成
次にRandomクラスの作成を行います。
乱数作成のコマンド
実際に乱数を作成するコマンドは次のものがあります。
nextInt(); | int型が取り得る範囲の乱数を生成する |
nextLong(); | long型が取り得る範囲の乱数を生成する |
nextDouble(); | 0.0~1.0のdouble型の乱数を生成する |
nextFloat(); | 0.0~1.0のfloat型の乱数を生成する |
nextBoolean(); | trueかfalseをランダムに取得する |
r.nextInt();
nextInt();だけは()の部分に数字を入れるだけで乱数を生成する範囲を指定することが出来ます。
ex) nextInt(10);
ここでは0~9の範囲で乱数を生成する。
乱数を使うときはこれらのコマンドに足し算、かけ算を組み合わせて使います。
例えば、10から19までの乱数を生成するには、
nextInt(10)+10;
とします。
これは、0~9までの乱数を生成しそれに10を足すことで10~19の範囲の乱数を生成しています。
スポンサーリンク
実際に使ってみる
最後にそれぞれの乱数の生成を実際にプログラムで書くとこうなります。
ソースコード
import java.util.Random;
public class Sample13 {
public static void main(String[] args) {
Random r=new Random();
int a=r.nextInt();
System.out.println(a);
int b=r.nextInt(10);
System.out.println(b);
int c=r.nextInt(10)+5;
System.out.println(c);
long d=r.nextLong();
System.out.println(d);
double e=r.nextDouble();
System.out.println(e);
float f=r.nextFloat();
System.out.println(f);
boolean g=r.nextBoolean();
System.out.println(g);
}
}
実行結果
1770509418
3
13
4788509745613059599
0.4252802507122345
0.4198233
false