我已尝试过以下代码..
public class GuessNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int number = rand.nextInt(100) + 1;
int guess;
System.out.println("Guess the number between 1 and 100");
System.out.println("");
guess = scan.nextInt();
while (guess < number) {
System.out.println("Higher!");
guess = scan.nextInt();
}
while (guess > number) {
System.out.println("Lower!");
guess = scan.nextInt();
}
while (guess == number) {
System.out.println("Correct!");
break;
}
}
}
我在向用户输入正确的号码之前无法询问。并在游戏结束时询问用户是否想再次玩游戏
答案 0 :(得分:4)
你在这里使用循环
while (guess < number) {
System.out.println("Higher!");
guess = scan.nextInt();
}
while (guess > number) {
System.out.println("Lower!");
guess = scan.nextInt();
}
while (guess == number) {
System.out.println("Correct!");
break;
}
是广告素材。它恰好有缺陷,但它非常有创意。你需要像
这样的东西while (guess != number) {
System.out.println((guess < number) ? "Higher!" : "Lower!");
guess = scan.nextInt();
}
System.out.println("Correct!");
答案 1 :(得分:0)
你只需要一个while循环。在你的循环中重新安排你的逻辑。
boolean isRunning = true;
while(isRunning){
guess = scan.nextInt();
if(guess < number){
System.out.println("Higher!");
}else if(guess > number){
System.out.println("Lower!");
}else if(guess == number){
System.out.println("Correct!");
//ask if need another input. (want to continue or not)
if(not continue){
break; or isRunning = false;
}
}
}
答案 2 :(得分:0)
逻辑不太正确。你想要一个while循环检查每个条件并继续询问一个新的数字,而猜测不等于数字。
while (guess != number) {
if (guess < number)
System.out.println("Higher!");
else
System.out.println("Lower!");
guess = scan.nextInt();
}
System.out.println("Correct!");
答案 3 :(得分:0)
while (true) {
if(guess < number)
System.out.println("Higher!");
else if(guess > number)
System.out.println("Lower!");
else if (guess == number){
System.out.println("Correct!");
}
guess = scan.nextInt();
}