为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

德玛西亚99 2024-01-05 15:11:21
我是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;}猜出数字后,程序会忽略询问用户是否想再次玩的那一行。为什么会发生这种情况?
查看完整描述

1 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

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

Scanner.nextLine当您使用after anyScanner.next*除其自身之外时,也会发生同样的情况nextLine。要解决这个问题,您可以Scanner.nextLine在每个之后调用Scanner.nextInt以消耗挂起的换行符


查看完整回答
反对 回复 2024-01-05
  • 1 回答
  • 0 关注
  • 40 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信