【发布时间】:2015-06-19 10:46:16
【问题描述】:
下面的代码是猜数游戏的一部分,其中计算机会在用户指定的范围内生成一个随机数。在这里,我试图将用户限制为 10 次猜测。如果他/她超过 10,则游戏结束:
int t1 = 0;//stores # of guesses
while(true){//loop begins
t1++;//increments each iteration to represent # of guesses
if(g1!=n){//if the guess is incorrect... (n = # user is trying to guess)
if(t1>10){//# of guesses cannot exceed 10
System.out.println("\nGAME OVER\nYou have exceeded the max # of tries!");
break;}//game ends if user exceeds max # of attempts
if(g1<n){System.out.println("\nGuess Higher!\n" + t1 + "attempt(s) so far");
continue;}//guess is too low
if(g1>n){System.out.println("\nGuess Lower!\n" + t1 + " attempt(s) so far");
continue;}}//guess is too high (loop ends)
我收到的输出只有 1/2 正确。例如,假设计算机生成了 1-100 范围内的数字 12。在用户第 10 次(最后一次)猜测时,它将打印:“GAME OVER...”;但是,如果用户的猜测太低或太高,它也会打印出来,这是我不想要的。
我要进行哪些更改来纠正此错误?我认为这与嵌套 if 中的“break”语句有关。
【问题讨论】:
-
您确定您使用的是正确的代码。这应该有效。另一方面,如果您只想循环到 10,那么为什么不使用
for loop或while (t1++ < 10)循环 -
你是对的。我修复了代码的另一个区域的错误,程序现在可以正常工作。我还实现了您在上面推荐的 while 循环。
标签: java if-statement while-loop break nested-if