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

时间:2014-07-22 02:19:34

标签: 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的变量。当我尝试改变循环内部的猜测时,它表示猜测是一个重复的局部变量"。

3 个答案:

答案 0 :(得分:4)

它说"重复变量"因为你宣布了两次:

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
}

答案 1 :(得分:0)

有一个重复的局部变量。这是:

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

答案 2 :(得分:0)

您已在循环之外声明guessint guess = scan.nextInt();)。你试图在循环中再次声明它,因此你得到了重复本地变量的消息。"

你应该删除循环中的声明 ,这样你的循环就像这样:

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