java 乱数を生成する

java 乱数を生成する

javaで、乱数を生成する手順を記述してます。

環境

  • OS windows11 home
  • java 17.0.2

手順

乱数を生成するには、「Math.random」で可能です。

Math.random()

実際に、使用してみます。

public class App {
    public static void main(String[] args) throws Exception {

        System.out.println(Math.random()); // 0.9330056985361999
        System.out.println(Math.random()); // 0.7915248342840314

    }
}

生成されていることが確認できます。

桁数を指定

桁数を指定する場合は、以下のように演算して切り上げを行います。

public class App {
    public static void main(String[] args) throws Exception {

        System.out.println(Math.ceil(Math.random() * 10)); // 3.0
        System.out.println(Math.ceil(Math.random() * 100)); // 90.0

    }
}