HOME > 乱数を取得する
乱数を取得する
乱数を取得するサンプルです。
乱数の取得には、java.util.Randomクラスを使用します。
サンプルコード
- 乱数を取得するサンプル
-
import java.util.Random; public class RandomSample { public static void main(String args[]) { //Randomクラスの生成 Random r = new Random(); //乱数の取得 int i = r.nextInt(50); //0~49の乱数を取得する double d = r.nextDouble(); //0.0~1.0の乱数を取得する boolean b = r.nextBoolean(); //true、falseいずれかを取得する //値の出力 System.out.println(i); System.out.println(d); System.out.println(b); } }
- 実行結果
- C:\>java RandomSample 14 0.6551267184080304 true
結果は実行毎に変わります
Randomクラス主要メソッド
戻値型 | メソッド | 説明 |
---|---|---|
boolean | nextBoolean() | trueまたはfalseいずれかを取得する (例)boolean b = r.nextBoolean(); |
int | nextInt() | int値が取りうる範囲で乱数を取得する (例)int i = r.nextInt(); |
int | nextInt(int i) | 0 ~ i-1の範囲で乱数を取得する (例)int i = r.nextInt(100); |
long | nextLong() | long値が取りうる範囲で乱数を取得する (例)long l = r.nextLong(); |
float | nextFloat() | 0.0f~1.0fの範囲で乱数を取得する (例)float f = r.nextFloat(); |
double | nextDouble() | 0.0d~1.0dの範囲で乱数を取得する (例)double d = r.nextDouble(); |