繁体   English   中英

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

[英]Can't change a variable made outside a while loop inside the loop

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的变量。 当我尝试在循环内部更改猜测时,它表示猜测是“重复的局部变量”。

它说“重复变量”,因为您两次声明了它:

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
}

确实有重复的局部变量。 这里是:

int guess = scan.nextInt();

更改为:

guess = scan.nextInt();

它将起作用。

什么问题?

当变量前面有类型名称时(例如int guessObject foo ),这就是Java中的声明。 并且它将隐藏先前的声明。 请参见以下示例:

int guess = 0; // we declare an int, named guess, and at the same time initialize it

for (...) { // with this curly braces, a new local scope starts
    // NOTE: in fact, curly braces start a new scope. the curly braces could be
    // there on it's own too. it does not have to be associated with a 
    // 'for', or a 'while', or a 'do-while', or an 'if'
    guess = 5; // this refers to the variable outside the scope, and overwrites it.

    // here be dragons!
    int guess = 2; // we're declaring an int, named 'guess' again. this will hide the former.
    guess = 8; // this refers to the locally declared variable, as the former one is hidden by it now
}

System.out.println(guess); // should print 5

您已经在循环外声明了guessint guess = scan.nextInt(); )。 您试图在循环内再次声明它,因此得到的消息是“重复的局部变量”。

您应该删除循环的声明以使循环看起来像这样:

        int guess = scan.nextInt();
        // ...
        while (guess != num) {
            // ...
            tries++;
            guess = scan.nextInt();
        }
        // ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM