Random库
概述
Random库主要用来生成随机数字。
Random库中的方法摘要:
使用步骤
三步:导包——创建——使用
代码示例(获取一个随机生产的int数字):
import java.util.Random;
public class TestRandom {
public static void main(String[] args) {
Random r = new Random();
int num = r.nextInt();
System.out.println("随机数:"+num);
}
}
输出如图:
生成一定范围内的随机数
random的方法nextInt() 可以重载一个参数。参数代表一个范围,是左闭右开区间。例如: int num = r.nextInt(3);
实际上代表的含义是:[0,3) 这样写固定从0开始
代码示例:
import java.util.Random;
public class TestRandom {
public static void main(String[] args) {
Random r = new Random();
for(int i = 0; i<10; i++) {
int num = r.nextInt(10);
System.out.println(num);
}
}
}
这段代码生成一段0~9之间的随机数字,输出结果如图:
指定生成随机数的范围,左右边界都指定
实现代码如下:
import java.util.Random;
public class TestRandom {
public static void main(String[] args) {
int n = 5;
Random r = new Random();
for(int i=0;i<10;i++) {
int result = r.nextInt(n)+1;
System.out.println(result);
}
}
}
这样就实现了**[1,5]内的随机数字生成。 如果需要生成[10,20],则在resulth后面+1改成+10**, n改成10
——————————————————————