使用nextInt()
方法
模拟需求:
班级需要一个点名器,输入班级最大学号,获得十个不同的随机学号
获取10个1-20之间的随机数,要求不能重复
import java.util.ArrayList;
import java.util.Random;
public class RandomDemo1 {
public static void main(String[] args) {
Random rnd = new Random();
ArrayList<Integer> StudentNumber = new ArrayList<>();
int i = 0;
while(i < 10) {
//该方法的作用是生成一个随机的int值,
//该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n
int number = rnd.nextInt(20)+1;
//判断学号是否重复
if(!StudentNumber.contains(number)) {
StudentNumber.add(number);
i++;
}
}
System.out.println(StudentNumber);
}
}
其中一个运行结果:[10, 17, 1, 12, 18, 2, 15, 6, 4, 5]
总结:Random.nextInt()方法可以生成一个随机数,范围是2^-31 ~ 2^31 - 1
,但在方法内传入参数(如m)后,随机数生成的范围变为[0,m)。
使用Math.random()
方法
模拟需求:
让用户输入范围[strat,end]
随机生成该范围内的一个随机数
import java.util.Scanner;
public class RandomDemo2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Start And End:");
int start = sc.nextInt();
int end = sc.nextInt();
System.out.println("output:"+ getrandom(start, end));
}
public static int getrandom(int start, int end) {
// int num = (int) (Math.random() * (end - start) + start);//不包括end
int num = (int) (Math.random() * (end - start + 1) + start);//包括end
return num;
}
}
运行结果:
Enter Start And End:
4 20
output: 6