当前位置: 移动技术网 > IT编程>开发语言>Java > Java中Random类的基本使用

Java中Random类的基本使用

2020年07月17日  | 移动技术网IT编程  | 我要评论
关于随机数对象Random:(1)产生一个随机数:测试代码:import java.util.Random;public class Test01 { public static void main(String[] args) { // 创建随机数对象 Random random = new Random(); // 随机产生一个int范围内的数字 int num1 = random.nextInt();

关于随机数对象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);
        }
    }
}

本文地址:https://blog.csdn.net/pipizhen_/article/details/107360161

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网