public int nextInt(int n):返回一个伪随机数,范围在 0(包括)和 指定值n (不包括)之间的int值。
使用Random类,完成生成3个10以内的随机整数的操作,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//1. 导包 import java.util.Random; publicclassDemo01_Random{ publicstaticvoidmain(String[] args){ //2. 创建键盘录入数据的对象 Random r = new Random(); for(int i = 0; i < 3; i++){ //3. 随机生成一个数据 int number = r.nextInt(10); //4. 输出数据 System.out.println("number:"+ number); } } }
备注:创建一个Random对象,每次调用nextInt()方法,都会生成一个随机数。
10.2.2 练习
获取随机数
获取1-n之间的随机数,包含n,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
// 导包 import java.util.Random; publicclassTest01Random{ publicstaticvoidmain(String[] args){ int n = 50; // 创建对象 Random r = new Random(); // 获取随机数 int number = r.nextInt(n) + 1; // 输出随机数 System.out.println("number:" + number); } }