[英]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 guess
或Object 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
您已經在循環外聲明了guess
( int guess = scan.nextInt();
)。 您試圖在循環內再次聲明它,因此得到的消息是“重復的局部變量”。
您應該刪除循環內的聲明,以使循環看起來像這樣:
int guess = scan.nextInt();
// ...
while (guess != num) {
// ...
tries++;
guess = scan.nextInt();
}
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.