【发布时间】:2020-02-07 10:22:54
【问题描述】:
我正在研究 1-100 的猜数,如果猜错了 7 次就会输掉比赛,除非你猜对了数字。我尝试使用 while 循环添加 if 语句 if (guess1 <8) break; 应该停止或中断我使用的正在运行的程序是 Unix Terminal。
import java.util.Random;
import java.util.Scanner;
public class Games {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Random rand = new Random();
int tries;
int correctNum = rand.nextInt(100);
int count = 7;
//int guess1 = input.nextInt();
while(true){
System.out.println("Pick a number between 1-100");
int guess1 = input.nextInt();
if(guess1 < correctNum){
System.out.println("Too low!");
} else if(guess1 > correctNum){
System.out.println("Too high!");
} else if(guess1 == correctNum){
System.out.println("Correct!");
} else{
System.out.println("hmm, try again");
}
if (guess1<8) break;
}
}
}
【问题讨论】:
-
其实,guess1 是用户输入的 Input,要循环检查的变量是 count。您应该从 1 而不是 7 开始计数,并在每次迭代时递增它。您也可以在
while(count < 8){中设置您的条件,而不是 `if (guess1 -
Games.java:15: error: cannot find symbol while(guess1 < 8){ ^ symbol: variable guess1 location: class Games 1 error -
guess1是用户输入的输入。创建另一个变量来跟踪attempts您也可以在此处使用do while。它执行代码,然后检查条件。 while 检查条件然后执行代码。
标签: java loops while-loop