gpt4 book ai didi

java - 如何在 Java 中的循环中重置变量?

转载 作者:行者123 更新时间:2023-11-29 10:11:13 26 4
gpt4 key购买 nike

我正在为我的计算机科学 1100 类(class)编写一个猜数游戏,其中一部分是打印玩家尝试猜测目标数​​字的次数。我定义了一个变量 tries 来跟踪它;每次玩家猜测时,程序都会将其递增 1。

游戏在玩家猜对数字后重新开始,此时我想重置 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!!");
}
}
}

最佳答案

a) 更改变量的范围

变量仅在它们定义的范围内可用。例如

while (something) { // all code inside the loop is in an inner scope
int variable = 42;
// variable is accessible here
}
// variable is not accessible here

这意味着,每次 while 循环执行一次迭代时,都会新创建变量。最好只在它们实际有意义的范围内定义变量(在本例中是在 while 循环中)。

b) 每次重新分配变量

另一种方法是在每次需要时重置变量。这将导致这样的设计:

int variable; // variable is defined outside the inner scope
while (something) {
variable = 42;
// some code that changes variable's value
}

关于java - 如何在 Java 中的循环中重置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33552953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com