如何在Java中每次获取不同的随机数:
import java.util.Random;
import java.util.Scanner;
public class Guess_tutorial {
public static void main(String[] args) {
Random random = new Random(100);
int rand_num = random.nextInt(100);
Scanner sc = new Scanner(System.in);
System.out.println("Enter your number: ");
int n = sc.nextInt();
while (n != rand_num) {
if (n > rand_num) {
System.out.println("Too high!");
} else {
System.out.println("Too low!");
}
n = sc.nextInt();
}
sc.close();
System.out.println("That's right!");
}
}
它始终是15.我做错了什么?试图学习Java。
答案 0 :(得分:7)
您正在将常量种子传递给Random
构造函数。不要这样做。并且它将默认为从时间推导出的种子。变化
Random random = new Random(100);
到
Random random = new Random();