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

标签 java while-loop io

程序代码:

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/

相关文章:

c - 在 C 中使用 while(1) 循环作为临时状态机?

c++ - 让 while 循环显示

python - Cython:使用 C++ 流

C - 程序只检查文件中的第一个单词

java - 使用不同的路径将war文件部署到Tomcat

java - c++ 将指针作为参数传递,而它在 java 中的对应物

java - 为什么 Swing 组件应该只在事件调度线程上访问?

java - 如何对 MAP 的项目进行排序并删除一个?

javascript - javascript问题时做

c - 如何在 C 中打开带有用户输入变量的文件?