How to specify the range of random numbers in Java?

In Java, you can use the Random class to generate random numbers and control the range of values by specifying a range. For example, to generate a random number between 1 and 100, you can use the following code:

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        Random rand = new Random();
        int randomNum = rand.nextInt(100) + 1; // 生成一个1到100之间的随机数
        System.out.println(randomNum);
    }
}

In the example above, rand.nextInt(100) will generate a random number between 0 and 99, and by adding 1, it changes the range to 1 to 100, making it easy to control the range of random numbers.

Leave a Reply 0

Your email address will not be published. Required fields are marked *