java在指定区间内生成随机数

Random对象生成随机数

首先需要导入包含Random的包 import java.util.Random;

nextInt(int)方法将生成0~参数之间的随机整数但不包括参数
例如生成0~99的随机整数:

import java.util.Random;
public class Test {
public static void main(String[] args){
  Random rand = new Random();
   System.out.println(rand.nextInt(100));
}
}

生成1 ~ 100之间的随机数为System.out.println(rand.nextInt(100) + 1); 但并不代表随意区间的生成关系为 (rand.nextInt(最大值) + 最小值)
区间范围的计算方式是: ((最大值 - 最小值 + 1) + 最小值);例如生成10 ~ 110之间的整数

System.out.println(rand.nextInt(101) + 10);

猜你喜欢

转载自www.cnblogs.com/prodigal-son/p/12805183.html