How can a random number be generated in Java?

In Java, you can generate random numbers using the java.util.Random class. Here is a simple example code:

import java.util.Random;

public class RandomNumberGenerator {
    public static void main(String[] args) {
        Random random = new Random();
        int randomNumber = random.nextInt(); // 生成一个随机整数
        System.out.println("随机数:" + randomNumber);
    }
}

In the above code, we created a Random object and then used the nextInt() method to generate a random integer. If you want to generate a random number within a specific range, you can use the nextInt(int bound) method, where the bound parameter specifies the upper limit of the random number (excluding).

int randomNumber = random.nextInt(100); // 生成一个0-99之间的随机整数
System.out.println("随机数:" + randomNumber);
bannerAds