Java中Random类的基本使用

关于随机数对象Random:

(1)产生一个随机数:

测试代码:

import java.util.Random;

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

        // 随机产生一个int范围内的数字
        int num1 = random.nextInt();
        System.out.println(num1);  // 范围为[Integer.MIN_VALUE, Integer.MAX_VALUE]之间的一个整数

        // 如果我要产生[0, 100]之间的整数怎么办
        int num2 = random.nextInt(101);
        System.out.println(num2);  // [0, 100]内的一个整数
        // 注意:nextInt(101)翻译为,下一个int类型的数据是101,表示只能取到100

    }
}

(2)产生[-100, 100]之间的随机数:

测试代码:

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

        // 打印一千个
        for (int i = 0; i < 1000; i++) {
            // 随机控制正负号,-1的0次方为1,-1的1次方为-1
            int fuhao = random.nextInt(2);  // 0或1
            fuhao = (fuhao == 0) ? 1 : -1;

            int num3 = random.nextInt(101) * fuhao;
            System.out.println(num3);
        }
    }
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值