如何在 Java 的循环中重置变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33552953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I reset a variable in a loop in Java?
提问by Seth Myers
I am writing a number-guessing game for my Computer Science 1100 class, one part of which is to print the number of attempts the player takes at guessing the target number. I've defined a variable tries
to track that; the program increments it by one every time the player makes a guess.
我正在为我的计算机科学 1100 课程编写一个猜数字游戏,其中一部分是打印玩家猜目标数字的尝试次数。我已经定义了一个变量tries
来跟踪它;每次玩家猜测时,程序都会将其加一。
The game restarts after the player guesses the number correctly, and at that point I want to reset the tries
counter. I can't figure out how to do that, however, because the program increments tries
each time the number is guessed. How can I do it?
在玩家正确猜出数字后游戏重新开始,此时我想重置tries
计数器。然而,我无法弄清楚如何做到这一点,因为tries
每次猜到数字时程序都会增加。我该怎么做?
import java.util.Scanner;
import java.util.Random;
public class Q2 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
Random r = new Random();
System.out.println("Welcome to the Number Guessing Game");
int x=0;//defining x for later
int tries = 1;//defining tries for later
while (x!=-1) {
int y = r.nextInt(101);//defining random number 0-100
System.out.print("Guess a number between 0 and 100 or enter -1 to quit: ");
x=kbd.nextInt();//redefining x
x=kbd.nextInt();//redefining x
for (int i=1;x!=-1&&x!=y;i=1) {//for loop
if (x<-1||x>100) {//illegal condition
System.out.print("Out of bounds. Try again: ");
}
else if (x>y) {//input greater than random condition
System.out.print("The number is lower. Try again: ");
}
else if (y>x) {//random greater than input condition
System.out.print("The number is higher. Try again: ");
}
x = kbd.nextInt();//redefining x
tries+=i;//defining pattern for tries
}
if (x==y) {//input=random condition
System.out.println("Congratulations! You guessed the number in " + tries + " tries");
}
}
if (x==-1) {//quit condition
System.out.print("Thank you for playing the game!!");
}
}
}
回答by Frithjof
a) Change the scope of your variable
a) 改变变量的作用域
Variables are only available in the scope they are defined in. For example
变量仅在定义它们的范围内可用。例如
while (something) { // all code inside the loop is in an inner scope
int variable = 42;
// variable is accessible here
}
// variable is not accessible here
This means, every time the while-loop performs one iteration, variable is newly created. It is a good practice to only define variables in the scope they actually have a meaning (in this case in the while-loop).
这意味着,每次 while 循环执行一次迭代时,都会新创建变量。一个好的做法是只在它们实际具有意义的范围内定义变量(在这种情况下是在 while 循环中)。
b) Assign the variable every time anew
b) 每次重新分配变量
Another way would be to reset the variable each time it is necessary. This would result in such a design:
另一种方法是在每次需要时重置变量。这将导致这样的设计:
int variable; // variable is defined outside the inner scope
while (something) {
variable = 42;
// some code that changes variable's value
}
回答by kdek
One possible solution would be to encapsulate your guessing game into it's own method, which will re-initialize all variables when called, and create an if
condition inside of your loop if the guess is correct.
一种可能的解决方案是将您的猜谜游戏封装到它自己的方法中,该方法将在调用时重新初始化所有变量,并if
在猜测正确时在循环内部创建一个条件。
private static void guessingGame() {
Scanner scanner = new Scanner(System.in);
double randomNum = Math.random();
double tries = 0, guess = 0;
do while (!(guess == randomNum) {
System.in("What is your guess? ");
guess = scanner.nextDouble();
tries++;
if (guess == randomNum) {
System.out.println("Guessed correctly in " + tries + " tries.");
tries = 0;
}
}
}
public static void main() {
guessingGame();
}