This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
                                
                                    (19个回答)
                                
                        
                                5个月前关闭。
            
                    
我是Java新手,正在尝试做一个猜谜游戏。在代码的一行中,我尝试从用户那里获取输入。但是,该程序似乎没有运行该行代码。为什么会这样呢?问题出现在我的主要方法中:

Scanner input = new Scanner(System.in);

System.out.println("Let's play a guessing game!");
while (true){
    // get a random number from 1 to 10
    int random = (int) (Math.random() * 10) + 1;
    System.out.println("I am thinking of a number between 1 and 10.");
    System.out.print("What do you think it is? ");
    int guess = input.nextInt();
    System.out.println((guess == random) ? "You are correct!":"You're wrong! The number was " + random);
    System.out.print("Play again? (Y/N)");

    // this line is where the problem occurred.
    String play = input.nextLine();
    if (play.equalsIgnoreCase("N"))
        break;
}


猜出一个数字后,该程序仅忽略了询问用户是否要再次播放的行。为什么会这样呢?

最佳答案

当您按下“ Enter”键时,Scanner.nextInt方法不会读取换行符,因此Scanner.nextLine在读取该换行符后立即返回。

当您在除Scanner.nextLine本身之外的任何Scanner.next*之后使用nextLine时,也会发生相同的情况。要解决此问题,您可以在每个Scanner.nextLine之后调用Scanner.nextInt以使用待处理的换行符。

关于java - 为什么程序无法从用户那里获得输入? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58583809/

10-12 01:40
查看更多