程序代码:
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之间:”这是一个很好的输出。但是,在我输入数字之前,它会立即输出,“你猜错了!请再试一次:”
如何修复此代码以实现预期的输出?
答案 0 :(得分:3)
问题在于您使用System.in.read()
。
System.in.read()
将逐个读取字符并将其作为int
返回。如果我输入1
,则System.in.read()
将返回49
,因为该字符1
被编码为。
为什么它会立即打印您的猜测错误而不让您输入任何内容的原因是System.in.read()
也会读取新行字符。如果有任何未读的内容,它会读取该内容,而不是要求新的输入。在您输入的Y
后面有一个换行符,因此它会读取该换行符。
您应该使用Scanner
:
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()
将返回用户输入的字符串输入,并忽略换行符。