Java Random Number Guide

In Java, you can use the java.util.Random class to generate random numbers. Below is a simple example code that demonstrates how to generate a random number ranging from 1 to 100.

import java.util.Random;

public class RandomNumberExample {
    public static void main(String[] args) {
        // 创建一个Random对象
        Random rand = new Random();
        
        // 生成一个1到100之间的随机数
        int randomNumber = rand.nextInt(100) + 1;
        
        // 输出随机数
        System.out.println("Random Number: " + randomNumber);
    }
}

In this example, we first create a Random object called rand. We then use the nextInt(int bound) method to generate a random number between 0 and 99, add 1 to the result, and thus get a random number between 1 and 100. Finally, we print out the random number.

bannerAds