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

乱数を0から9の範囲から生成する方法は、2つあります。
Random
1つは、Randomクラスを使う方法です。
まず、Randomをインポートします。
import java.util.Random;
次に、Randomクラスをインスタンス化します。
RandomクラスのインスタンスからnextInt()を呼び出します。
そして、nextInt()の引数に10を指定します。
Random rnd = new Random();
int value = rnd.nextInt(10);
上記のnextInt()は、0から9の範囲から乱数を生成します。
使用例
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(10);
System.out.print(value + " ");
}
}
}
出力:
7 3 3 0 2 5 7 1 2 6
Math.random()
もう1つは、Math.random()を使う方法です。
まず、Math.random()を呼び出します。
そして、Math.random()の戻り値に9を掛けます。
double value = Math.random() * 9;
上記の計算で、1から9までの範囲の乱数を取得できます。
もし、生成する乱数を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() * 9);
System.out.print(value + " ");
}
}
}
出力:
10 29 88 77 15 51 39 88 70 6
まとめ
乱数を0から9の範囲から生成する方法は、次の2つです。
- Randomを使う方法
Random rnd = new Random();
int value = rnd.nextInt(10);
- Math.random()を使う方法
double value = Math.random() * 9;
コメント