java - 无法在循环内的 while 循环外更改变量

标签 java loops variables

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/

相关文章:

sql - 基于日期字段更新表而不使用sql循环

php - 使用 php 发送变量的最安全方式

c - 如何将用户输入存储为 c 中的变量?

java - 如何在 Android 中使用 facebook api 注销

java - h2o - 无法找到或加载主类代码 7 错误

java - 针对 : while (true) 的优化

python - 从另一个文件导入和更改变量

java - 是否可以在谷歌应用引擎上部署 cakephp 应用程序?

java - 如何使用速度模板将选定的 href <a> 标签值发送回 java 方法

tsql - PostgreSQL 在函数外循环。那可能吗?