java生成指定范围的随机数

5,794 阅读1分钟
//获得 [1, 100] 的 10 个取值
public class Test {
public static void main(String[] args){
Random rand = new Random();
        for(int i=0; i<10; i++) {
        System.out.println(rand.nextInt(100) + 1);
        }
    }
}

//生成区间 [64,128] 中随机值的代码为:

rand.nextInt(65)+ 64;

最终公式:

//randNumber 将被赋值为一个 MIN 和 MAX 范围内的随机数
int randNumber =rand.nextInt(MAX - MIN + 1) + MIN;