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

乱数を1から10の範囲から生成する方法は、2つあります。
Random
1つは、Randomクラスを使う方法です。
まず、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から11の範囲の乱数になります。
使用例
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
Math.random()
もう1つは、Math.random()を使う方法です。
まず、Math.random()を呼び出します。
Math.random()の戻り値に10を掛けます。
そして、Math.random()と10の掛け算の結果に1を足します。
double value = Math.random() * 10 + 1;
上記の計算で、1から10の範囲の乱数を取得できます。
もし、生成する乱数をint型として取得したい場合は、上記の計算の結果を(int)で変換します。
int value = (int)(Math.random() * 10 + 1);
使用例
public class Main {
public static void main(String[] args){
for(int i = 0; i < 5; i++) {
int value = (int)(Math.random() * 10 + 1);
System.out.println(value);
}
}
}
出力:
8
2
2
9
5
まとめ
乱数を1から10の範囲から生成する方法は、次の2つです。
- Randomを使う方法
Random rnd = new Random();
int value = rnd.nextInt(11) + 1;
- Math.random()を使う方法
double value = Math.random() * 10 + 1;
コメント