Java Random Class Tutorial

In Java, the Random class is used for generating pseudo-random numbers. Below is a simple example demonstrating how to use the Random class.

import java.util.Random;

public class RandomExample {
    public static void main(String[] args) {
        Random random = new Random();
        
        // 生成一个随机整数
        int randomNumber = random.nextInt();
        System.out.println("随机整数:" + randomNumber);
        
        // 生成一个在0到10之间的随机整数
        int randomInRange = random.nextInt(10);
        System.out.println("0到10之间的随机整数:" + randomInRange);
        
        // 生成一个在50到100之间的随机浮点数
        double randomDouble = random.nextDouble() * 50 + 50;
        System.out.println("50到100之间的随机浮点数:" + randomDouble);
        
        // 生成一个随机布尔值
        boolean randomBoolean = random.nextBoolean();
        System.out.println("随机布尔值:" + randomBoolean);
    }
}

In the example above, an instance of the Random class is created and used to generate various types of random numbers. The nextInt() method can be used to generate random integers, passing parameters to generate integers within a specified range, the nextDouble() method to generate random floating-point numbers, and the nextBoolean() method to generate random Boolean values.

bannerAds