随机生成正整数: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);
}
}