How to write code for generating random numbers in Java?

In Java, you can generate random numbers using either the Random class or the random() method in the Math class. Here are two common ways to do this:

  1. Use the Random class:
import java.util.Random;

public class RandomNumber {
    public static void main(String[] args) {
        // 创建一个Random对象
        Random random = new Random();

        // 生成一个随机整数
        int randomNumber = random.nextInt();

        // 生成一个指定范围的随机整数
        int randomNumberInRange = random.nextInt(100); // 生成0到99之间的随机整数

        // 生成一个随机浮点数
        double randomDouble = random.nextDouble();

        // 输出结果
        System.out.println("随机整数: " + randomNumber);
        System.out.println("指定范围的随机整数: " + randomNumberInRange);
        System.out.println("随机浮点数: " + randomDouble);
    }
}
  1. Using the random() method of the Math class:
public class RandomNumber {
    public static void main(String[] args) {
        // 生成一个随机浮点数
        double randomDouble = Math.random();

        // 生成一个指定范围的随机整数
        int randomNumberInRange = (int) (Math.random() * 100); // 生成0到99之间的随机整数

        // 输出结果
        System.out.println("随机浮点数: " + randomDouble);
        System.out.println("指定范围的随机整数: " + randomNumberInRange);
    }
}

Note: The code above is a simple example, it may need appropriate modifications based on specific requirements for actual applications.

bannerAds