这里举例两种方法:
方法1:Math.random()
for (int i = 0; i < 30; i++) {
// 最小值:1 + 0.0*10 = 1 + 0 =1
// 最大值:1 + 0.99*10 = 1 + 9.9 = 10.9 = 10
System.out.println((int) (1 + Math.random() * 10));
}
通过java.Math包的random方法得到1-10的int随机数
公式是:最小值---最大值(整数)的随机数
(类型)最小值+Math.random()*最大值
方法2: random.nextInt(int value)
//打印 70到80之间的随机数
int min = 70;
int max = 80;
Random random = new Random();
// random.nextInt(10) 返回0 - 10 之间的伪随机数 [0 - 10 ),包括0 不包括10
// 最小值:(80 - 70) + 70 = 0 + 70 = 70
// 最大值:(80 - 70) + 70 = 9 + 70 = 79
System.out.println( random.nextInt(max-min) + min );
公式:random.nextInt(最大值 - 最小值) + 最小值
详细参考文章:随机数