どうも、ちょげ(@chogetarou)です。
Randomを使って乱数を0から9の範囲で生成する方法を紹介します。
方法
Randomを使って乱数を0から9の範囲で生成するには、メソッドを使います。
まず、Randomをインポートします。
import java.util.Random;
次に、Randomクラスをインスタンス化します。
RandomクラスのインスタンスからnextInt()を呼び出します。
そして、nextInt()の引数に10を指定します。
Random rnd = new Random();
int value = rnd.nextInt(10);
上記のnextInt()は、0から9の範囲から乱数を生成します。
使用例
import java.util.Random;
public class Main {
public static void main(String[] args) throws Exception {
Random rnd = new Random();
for(int i = 0; i < 10; i++) {
int value = rnd.nextInt(10);
System.out.print(value + " ");
}
}
}
出力:
7 3 3 0 2 5 7 1 2 6
コメント