java.util.Random类,用来生成随机数字
一、常用方法
// 构造方法
public Random() // 使用当前机器时间作为种子创建 Random 对象
public Random(long seed) // 使用参数 seed 指定的种子创建 Random 对象
// 常用方法
public boolean nextBoolean() // 随机得到 true 或 false
public int nextInt() // 从 Integer.MIN_VALUE 到 Integer.MAX_VALUE
public long nextLong() // 从 Long.MIN_VALUE 到 Long.MAX_VALUE
public float nextFloat() // 在 [0.0, 1.0) 之间均匀分布的 float 值
public double nextDouble() // 在 [0.0, 1.0) 之间均匀分布的 double 值
public int nextInt(int bound) // [0,bound),左闭右开区间,类比数组长度、索引
public void nextBytes(byte[] bytes) // 生成随机字节数并将其置于用户提供的byte数组中
二、练习使用
Random ran = new Random();
System.out.println(ran.nextInt());
System.out.println(ran.nextInt(2)); // [0, 1]
System.out.println(ran.nextFloat());
System.out.println((int) (ran.nextDouble() * 100)); // [0, 99]
System.out.println(ran.nextBoolean());
byte[] arr = new byte[5];
ran.nextBytes(arr);
System.out.println(Arrays.toString(arr)); // [19, 34, -68, 68, 115]
具有相同种子的两个 Random 对象,调用 nextInt 方法获取的随机数序列相同
Random ran1 = new Random(100);
Random ran2 = new Random(100);
System.out.println(ran1.nextInt()); // -1193959466
System.out.println(ran2.nextInt()); // -1193959466
三、练习题
Scanner 的 nextInt() 方法用来获取输入数字,小括号内可以指定输入数的解析基数
Random 的 nextInt() 方法用来生成随机数字,小括号内可以指定随机数的取值范围
1、1 ~ 10 之间随机得到 10 个不同的数
// 两两对比,嵌套循环,两个指针
Random ran = new Random();
int arr[] = new int[10];
for (int i = 0; i < 10; i++) {
arr[i] = ran.nextInt(100) + 1; // 范围[1,n],整体+1
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) { // 和之前所有的比较,发现相同,索引i-1
i--;
}
}
}
System.out.println(Arrays.toString(arr));
2、猜数字小游戏,折半思维,效率更高
public class RandomDemo {
public static void main(String[] args) {
Random ran = new Random(); // 生成随机数
Scanner scan = new Scanner(System.in); // 获取输入数
int randomNum1 = ran.nextInt(100) + 1; // [1,100]
System.out.println("*****猜数字小游戏,有无数次机会*****");
System.out.println("随机数范围为[1,100],请输入您猜测的数字:");
int count1 = 0; // 记录猜数次数
while (true) { // 一直重试,用死循环
int guessNum = scan.nextInt();
if (guessNum > randomNum1) {
count1++;
System.out.println("您输入的数字过大,请重新输入:");
} else if (guessNum < randomNum1) {
count1++;
System.out.println("您输入的数字过小,请重新输入:");
} else {
count1++;
System.out.println("恭喜您,猜中了,游戏结束!一共猜测了" + count1 + "次");
break; // 如果猜中,则退出循环
}
}
int randomNum2 = ran.nextInt(100) + 1; // [1,100]
System.out.println("*****猜数字小游戏,只有五次机会*****");
System.out.println("随机数范围为[1,100],请输入您猜测的数字:");
int count2 = 5; // 记录猜数次数
for (int i = 0; i < 5; i++) { // 固定次数,for循环
int guessNum = scan.nextInt();
if (guessNum > randomNum2) {
count2--;
System.out.println(count2 == 0 ?
"抱歉,机会用完,请重新开始游戏!答案为" + randomNum2 :
"您输入的数字过大,还有" + count2 + "次机会,请重新输入:");
} else if (guessNum < randomNum2) {
count2--;
System.out.println(count2 == 0 ?
"抱歉,机会用完,请重新开始游戏!答案为" + randomNum2 :
"您输入的数字过小,还有" + count2 + "次机会,请重新输入:");
} else {
count2--;
System.out.println("恭喜您,猜中了,游戏结束!");
break; // 如果猜中,则退出循环
}
}
}
}