どうも、ちょげ(@chogetarou)です。
Random.nextInt()で乱数に最大値を設定する方法を紹介します。
方法

Random.nextInt()で乱数に最大値を設定するには、引数を使います。
まず、Randomのインスタンスを生成します。
インスタンスからnextInt()を呼び出します。
そして、nextInt()の引数に最大値を指定します。
Random rnd = new Random();
rnd.nextInt(max) //max=最大値
上記のnextInt()は、0から最大値までの乱数を生成します。
使用例
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Random rnd = new Random();
for (var i = 0; i < 10; i++) {
System.out.println(rnd.nextInt(10));
}
}
}
出力:
6
0
7
9
3
9
1
6
7
1
コメント