どうも、ちょげ(@chogetarou)です。
Randomを使って乱数を1から10の範囲で生成する方法を紹介します。
方法

Randomを使って乱数を1から10の範囲で生成するには、nextInt()を使います。
まず、Randomをインポートします。
import java.util.Random;
次に、Randomクラスをインスタンス化します。
RandomクラスのインスタンスからnextInt()を呼び出します。
そして、nextInt()の引数に11を指定し、nextInt()の戻り値に1を足します。
Random rnd = new Random();
int value = rnd.nextInt(11) + 1;
上記のnextInt()に1を足した値は、1から10の範囲の乱数になります。
使用例
import java.util.Random;
public class Main {
public static void main(String[] args) throws Exception {
Random rnd = new Random();
for(int i = 0; i < 5; i++) {
int value = rnd.nextInt(11) + 1;
System.out.println(value);
}
}
}
出力:
3
8
2
4
7
コメント