为什么程序无法获取用户的输入?

我是Java新手,我正在尝试制作一个猜谜游戏。在我的一行代码中,我尝试获取用户的输入。但是,该程序似乎没有运行该行代码。为什么会发生这种事?问题出现在我的main方法中:


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;

}

猜出数字后,程序会忽略询问用户是否想再次玩的那一行。为什么会发生这种情况?


德玛西亚99
浏览 46回答 1
1回答

蝴蝶不菲

当您按“Enter”键时,该Scanner.nextInt方法不会读取换行符,因此在读取该换行符Scanner.nextLine后立即返回。Scanner.nextLine当您使用after anyScanner.next*除其自身之外时,也会发生同样的情况nextLine。要解决这个问题,您可以Scanner.nextLine在每个之后调用Scanner.nextInt以消耗挂起的换行符。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java