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

Mathを使ってint型の乱数を生成するには、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
コメント