当前位置: 代码迷 >> 综合 >> Random 随机数类
  详细解决方案

Random 随机数类

热度:87   发布时间:2023-12-01 23:29:07.0

随机生成正整数:public int nextInt (int bound)

随机生成正整数的范围为 [0,bound),左闭右开

public class Demo {public static void main(String[] args) {//创建随机数对象Random r = new Random();//生成0~7之间的正整数int num = r.nextInt(8);System.out.println(num);}
}

若要指定生成正整数范围为[max,min],可以 r.nextInt(max - min + 1) + min

public class Demo {public static void main(String[] args) {//随机生成[3,6]之间的正整数Random r = new Random();int num = r.nextInt(4) + 3;System.out.println(num);}
}