跳转至

Random类

Random是Java中用于生成伪随机数的类,提供了各种随机数生成方法。

作用

Random类的主要优势在于:

  1. 提供多种随机数生成方法
  2. 可以设置随机数种子,保证可重复性
  3. 支持各种数据类型的随机数生成
  4. 适合模拟、测试、游戏等场景

例子

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

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

        // 生成随机整数
        System.out.println("随机整数: " + random.nextInt());
        System.out.println("0-100随机整数: " + random.nextInt(100));

        // 生成随机浮点数
        System.out.println("随机浮点数: " + random.nextFloat());
        System.out.println("随机双精度数: " + random.nextDouble());

        // 生成随机布尔值
        System.out.println("随机布尔值: " + random.nextBoolean());

        // 生成随机字节数组
        byte[] bytes = new byte[5];
        random.nextBytes(bytes);
        System.out.println("随机字节数组: " + Arrays.toString(bytes));

        // 使用种子创建Random对象
        Random seededRandom = new Random(12345);
        System.out.println("种子随机数1: " + seededRandom.nextInt(100));
        System.out.println("种子随机数2: " + seededRandom.nextInt(100));

        // 使用ThreadLocalRandom(Java7+)
        ThreadLocalRandom tlr = ThreadLocalRandom.current();
        System.out.println("线程本地随机数: " + tlr.nextInt(1, 100));

        // 生成指定范围的随机数
        int min = 10;
        int max = 20;
        int rangeRandom = random.nextInt(max - min + 1) + min;
        System.out.println("范围随机数: " + rangeRandom);

        // 生成随机字符串
        String chars = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        System.out.println("随机字符串: " + sb.toString());
    }
}

思考

上述生成随机字符串的例子中,为什么是“ABCDEFGHJKMNPQRSTUVWXYZ23456789”?

为什么没有 L I O 0 ?