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

乱数を1から100の範囲から生成する方法は、2つあります。
Random
1つは、Randomクラスを使う方法です。
まず、Randomをインポートします。
import java.util.Random;
次に、Randomクラスをインスタンス化します。
RandomクラスのインスタンスからnextInt()を呼び出します。
そして、nextInt()の引数に101を指定し、nextInt()の戻り値に1を足します。
Random rnd = new Random();
int value = rnd.nextInt(101) + 1;
上記のnextInt()に1を足した値は、1から101の範囲の乱数になります。
使用例
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(101) + 1;
System.out.print(value + " ");
}
}
}
出力:
32 85 50 50 84 24 88 89 58 97
Math.random()
もう1つは、Math.random()を使う方法です。
まず、Math.random()を呼び出します。
Math.random()の戻り値に100を掛けます。
そして、Math.random()と100の掛け算の結果に1を足します。
double value = Math.random() * 100 + 1;
上記の計算で、1から100までの範囲の乱数を取得できます。
もし、生成する乱数をint型として取得したい場合は、上記の計算の結果を(int)で変換します。
int value = (int)(Math.random() * 100 + 1);
使用例
public class Main {
public static void main(String[] args) throws Exception {
for(int i = 0; i < 10; i++) {
int value = (int)(Math.random() * 100 + 1);
System.out.print(value + " ");
}
}
}
出力:
10 29 88 77 15 51 39 88 70 6
まとめ
乱数を1から100の範囲から生成する方法は、次の2つです。
- Randomを使う方法
Random rnd = new Random();int value = rnd.nextInt(101) + 1; - Math.random()を使う方法
double value = Math.random() * 100 + 1;





コメント