在您的代码中,您实际上从未调用过您的generateSecretNumber()
方法,而是声明了一个变量。删除 main 中的声明,并将打印行更改为System.out.print("Random number is: " + generateSecretNumber());
.
接下来,该generateSecretNumber()
方法不应该有任何参数,因为它完全由它自己决定要做什么,并且不需要任何外部数据。由于参数没有了,你还需要int w, x, y, z;
在它的开头声明。
其次,您正在生成一个没有上限的随机整数。这根本不是您想要的,相反,您的rand.nextInt()
调用上限应该是 10,导致rand.nextInt(10)
. 这将选择一个从 0 到 9 的随机整数。
最后,您返回的是数字的总和,而不是他们实际生成的四位数。相反,返回每个数字的总和乘以它们的位置。例如,第四位数字应该是w * 1000
。
结果代码示例:
public class RandUniqueFourDigits {
public static void main(String[] args) {
System.out.println("Random number is: " + generateSecretNumber());
}
public static int generateSecretNumber() {
Random rand = new Random();
int w = 0, x = 0, y = 0, z = 0;
// Generate each digit until they're all unique
while(w == x || w == y || w == z || x == y || x == z || y == z) {
w = rand.nextInt(10);
x = rand.nextInt(10);
y = rand.nextInt(10);
z = rand.nextInt(10);
}
// Generate each digit until they're all unique
w = rand.nextInt(10);
do x = rand.nextInt(10); while(x == w)
// Combine them into one integer and return
return w * 1000 + x * 100 + y * 10 + z;
}
}
对于更有效的循环(每个数字仅在需要时重新生成,就像您的初始代码一样),将 while 循环完全替换为:
w = rand.nextInt(10);
do x = rand.nextInt(10); while(x == w);
do y = rand.nextInt(10); while(y == w || y == x);
do z = rand.nextInt(10); while(z == w || z == x || z == y);
导致:
public class RandUniqueFourDigits {
public static void main(String[] args) {
System.out.println(generateSecretNumber());
}
public static int generateSecretNumber() {
Random rand = new Random();
int w = 0, x = 0, y = 0, z = 0;
// Generate each digit until they're all unique
w = rand.nextInt(10);
do x = rand.nextInt(10); while(x == w);
do y = rand.nextInt(10); while(y == w || y == x);
do z = rand.nextInt(10); while(z == w || z == x || z == y);
// Combine them into one integer and return
return w * 1000 + x * 100 + y * 10 + z;
}
}