public class Cow {
public static void main(String [ ] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Figure out a number between 1 and 100");
int num = 4;
int guess = scan.nextInt();
if (guess == num) {
System.out.println("Congratulations, you got it on your first try!");
}
int tries = 1;
while (guess != num) {
System.out.println("Incorrect. You have guessed: " + tries
+ " times. Guess again!");
tries++;
int guess = scan.nextInt();
}
System.out.println("You have figured it out in " + tries + " tries.");}
}
}
我在 while 循环外创建了一个名为 guess 的变量。当我尝试在循环内更改 guess 时,它说 guess 是一个“重复的局部变量”。
最佳答案
它说“重复变量”,因为你声明了它两次:
int guess = scan.nextInt();
//...
while (guess != num) {
//...
int guess = scan.nextInt();
}
移除修饰符:
int guess = scan.nextInt();
//...
while (guess != num) {
//...
guess = scan.nextInt();
}
可能是一个更简单的解决方案:
int guess;
while ((guess = scan.nextInt()) != num) {
//do code
}
关于java - 无法在循环内的 while 循环外更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24877867/