gpt4 book ai didi

Java .nextLine() 重复行

转载 作者:搜寻专家 更新时间:2023-10-31 08:09:59 30 4
gpt4 key购买 nike

我的猜谜游戏一切正常,但是当涉及到询问用户是否想再玩的部分时,它会重复这个问题两次。但是我发现,如果我将输入法从 nextLine() 更改为 next(),它不会重复问题。这是为什么?

这里是输入和输出:

I'm guessing a number between 1-10
What is your guess? 5
You were wrong. It was 3
Do you want to play again? (Y/N) Do you want to play again? (Y/N) n

这是代码:(它是用Java编写的)最后一个 do while 循环 block 是询问用户是否想再次玩的部分。

import java.util.Scanner;

public class GuessingGame
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean keepPlaying = true;

System.out.println("Welcome to the Guessing Game!");

while (keepPlaying) {
boolean validInput = true;
int guess, number;
String answer;

number = (int) (Math.random() * 10) + 1;
System.out.println("I'm guessing a number between 1-10");
System.out.print("What is your guess? ");
do {
validInput = true;
guess = input.nextInt();
if (guess < 1 || guess > 10) {
validInput = false;
System.out.print("That is not a valid input, " +
"guess again: ");
}
} while(!validInput);
if (guess == number)
System.out.println("You guessed correct!");
if (guess != number)
System.out.println("You were wrong. It was " + number);
do {
validInput = true;
System.out.print("Do you want to play again? (Y/N) ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y"))
keepPlaying = true;
else if (answer.equalsIgnoreCase("n"))
keepPlaying = false;
else
validInput = false;
} while (!validInput);
}
}
}

最佳答案

在您的 do while 循环中,您不需要 nextLine(),您只需要 next()

所以改变这个:

answer = input.nextLine();

为此:

answer = input.next();

请注意,正如其他人所建议的那样,您可以将其转换为 while 循环。这样做的原因是,do while 循环用于需要至少执行一次循环,但不知道需要多久执行一次的情况。虽然在这种情况下它肯定是可行的,但这样的事情就足够了:

System.out.println("Do you want to play again? (Y/N) ");
answer = input.next();
while (!answer.equalsIgnoreCase("y") && !answer.equalsIgnoreCase("n")) {
System.out.println("That is not valid input. Please enter again");
answer = input.next();
}

if (answer.equalsIgnoreCase("n"))
keepPlaying = false;

只要未输入“y”或“n”(忽略大小写),while 循环就会一直循环。只要它是,循环就结束了。 if 条件会在必要时更改 keepPlaying 值,否则什么也不会发生,您的外部 while 循环将再次执行(从而重新启动程序)。

编辑:这解释了为什么您的原始代码不起作用

我应该补充一点,您的原始语句不起作用的原因是您的第一个 do while 循环。在其中,您使用:

guess = input.nextInt();

这会读取行外的数字,但不会返回行,这意味着当您使用:

answer = input.nextLine();

它会立即从 nextInt() 语句中检测到剩余的回车符。如果你不想使用我的解决方案,只阅读 next(),你可以通过这样做吞下剩下的:

guess = input.nextInt();
input.nextLine();
rest of code as normal...

关于Java .nextLine() 重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18320738/

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