どうも、ちょげ(@chogetarou)です。
int型(整数)の乱数を生成する方法を紹介します。
方法

int型の乱数を生成する方法は、2つあります。
Random
1つは、Randomクラスを使う方法です。
まず、Randomをインポートします。
import java.util.Random;
次に、Randomクラスをインスタンス化します。
そして、RandomクラスのインスタンスからnextInt()を呼び出します。
Random rnd = new Random();
int result = rnd.nextInt();
上記のnextInt()は、乱数を生成します。
もし、生成する乱数に範囲をつけたい場合は、nextInt()の引数に最大値を指定します。
//max=最大値
int result = rnd.nextInt(max);
引数に最大値を指定したnextInt()は、0から最大値までの乱数を生成します。
使用例
import java.util.Random;
public class Main {
public static void main(String[] args) throws Exception {
Random rnd = new Random();
for(var i = 0; i < 5; i++) {
System.out.println(rnd.nextInt(10));
}
}
}
出力:
5
3
2
4
7
Math.random()
もう1つは、Math.random()を使う方法です。
まず、Math.random()を呼び出します。
Math.random()に乱数の最大値を掛けます。
そして、Math.random()に最大値を掛けた結果を int型に変換します。
//max=最大値
int result = (int)(Math.random() * max)
上記の変換は、0から最大値までの乱数を生成します。
もし、生成する乱数に最小値を追加したい場合は、Math.random()に最大値と最小値の差を掛けます。
そして、掛け算の結果に最小値を足し、その和をint型に変換します。
//max=最大値, min=最小値
int result = (int)(Math.random() * (max - min) + min);
使用例
public class Main {
public static void main(String[] args) throws Exception {
for(int i = 0; i < 5; i++) {
System.out.println((int)(Math.random() * 10));
}
}
}
出力:
8
3
2
2
3
まとめ
int型(整数)の乱数を生成する方法は、次の2つです。
- Randomを使う方法
Random rnd = new Random();
int result = rnd.nextInt();
- Math.random()を使う方法
int result = (int)(Math.random() * max)
コメント