【问题标题】:stop the program when user press enter key当用户按下回车键时停止程序
【发布时间】:2020-12-20 05:56:05
【问题描述】:

请测试我的代码。 当用户按下回车键或不发短信时,我试图终止我的程序。但我的程序没有终止。请帮帮我!

Scanner s = new Scanner(System.in);
        String a =s.nextLine();
        
        while(s.hasNext())
        {
            System.out.println(s.nextLine());
        }

【问题讨论】:

  • 你的程序在 EOF 字符被输入时终止。
  • 您可以通过键入 control-d 或 control-z 来结束此操作。

标签: java


【解决方案1】:

您希望它回显用户输入的任何内容,直到他们在没有输入任何内容的情况下按 Enter 键?

Scanner s = new Scanner(System.in);
String a = s.nextLine();
while(!a.equals("")) {
    System.out.println(a);
    a = s.nextLine();
}

【讨论】:

  • 您的代码在 while 语句中存在错误。必须是!a.equals(""),然后才能工作。
  • 谢谢!在我的手机浏览器中编码的危险。
【解决方案2】:

这个帖子可能会对你有所帮助。 Java Scanner hasNext() doesn't return false

您的 s.hasNext() 在您的代码中处于挂起状态,因为 Scanner 在 System.in 上

【讨论】:

    猜你喜欢
    • 2014-03-28
    • 2016-12-19
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多