gpt4 book ai didi

java - while 循环中的代码行在错误的时间执行

转载 作者:行者123 更新时间:2023-12-01 20:11:11 25 4
gpt4 key购买 nike

程序代码:

public static void main(String[] args) throws IOException {

System.out.print("Welcome to my guessing game! "
+ "Would you like to play (Y/N)? ");
yesOrNoAnswer = (char)System.in.read();

if(yesOrNoAnswer == 'Y') {
System.out.print("\n\nGuess the number (between 1 and 10): ");
while(AnswerIsCorrect == false) {
guess = System.in.read();

if(guess == correctAnswer) {
AnswerIsCorrect = true;
}
else {
System.out.print("\nYou guessed wrong! Please try again: ");
}
}
System.out.print("You guessed correct! Congratulations!"
+ "\n\nPress any key to exit the program . . .");
System.in.read();
}
}

预期输出:

Welcome to my guessing game! Would you like to play (Y/N)? Y


Guess the number (between 1 and 10):

实际输出:

Welcome to my guessing game! Would you like to play (Y/N)? Y


Guess the number (between 1 and 10):
You guessed wrong! Please try again:

当我在第一个问题(你想玩吗)输入“Y”时,它会继续输出“猜猜 1 到 10 之间的数字:”这是一个很好的输出。然而,在我输入数字之前,它立即输出:“您猜错了!请重试:”

如何修复此代码以实现预期输出?

最佳答案

问题在于您对 System.in.read() 的使用。

System.in.read() 将一一读取字符并将其作为 int 返回。如果我输入 1System.in.read() 将返回 49,因为这就是字符 1 的含义编码为。

它立即打印出您的猜测是错误的而不让您输入任何内容的原因是 System.in.read() 也会读取换行符。如果有任何未读的内容,它会读取该内容,而不是要求新的输入。您输入的 Y 之后有一个新行字符,因此它会读取该新行字符。

您应该使用扫描仪:

    Scanner scanner = new Scanner(System.in); // create a new scanner
System.out.print("Welcome to my guessing game! "
+ "Would you like to play (Y/N)? ");
yesOrNoAnswer = scanner.nextLine().charAt(0); // reading the first character from the next line

if(yesOrNoAnswer == 'Y') {
System.out.print("\n\nGuess the number (between 1 and 10): ");
while(AnswerIsCorrect == false) {
guess = Integer.parseInt(scanner.nextLine()); // get an int from the next line

if(guess == correctAnswer) {
AnswerIsCorrect = true;
}
else {
System.out.print("\nYou guessed wrong! Please try again: ");
}
}
System.out.print("You guessed correct! Congratulations!"
+ "\n\nPress any key to exit the program . . .");
scanner.nextLine();
}

Scanner.nextLine() 将返回用户以字符串形式键入的输入,并忽略换行符。

关于java - while 循环中的代码行在错误的时间执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46680460/

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