Java基础(5) | Random

# 什么是Random?

Random用于生成随机数。

# 使用示例

package com.leerep.javabase.random;

import java.util.Random;

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

        //整数范围内随机值:
        int num = r.nextInt();
        System.out.println(num);

        //区间[0, n)之间取值:
        int num1 = r.nextInt(10);
        System.out.println(num1);

        //区间[1, n]之间取值:
        int num2 = r.nextInt(10) + 1;
        System.out.println(num2);

        //true,false随机
        boolean b = r.nextBoolean();
        System.out.println(b);

    }
}

posted @ 2021-02-05 22:33  扶-9  阅读(98)  评论(1)    收藏  举报