【问题标题】:How to capture enter key, using scanner as console input?如何使用扫描仪作为控制台输入来捕获输入键?
【发布时间】:2014-06-05 08:01:27
【问题描述】:

我想在控制台中捕获输入字符。我正在输入 2 个字符串。

案例 1. removestudent(按回车键)从数组列表中删除所有学生。

案例2.removestudent student1 从数组列表中删除students1。

Scanner in=new Scanner();

type_op=in.next();

param=in.next();

if (type_op.equals("removestudent"))
{

    //Calling remove student function and passing param over here.

}

现在案例 2 工作正常。但是,对于案例 1,我希望当用户按 Enter 时参数值为 null。然后,我将 param 作为空值传递给我的删除函数,并删除数组列表中的所有学生。

list1.clear();

请帮助我了解如何获取此输入键。

【问题讨论】:

  • scanner.nextLine() 可以与 size() 或 isEmpty() 一起使用
  • scanner.nextLine() 将不起作用,因为我试图在用户按 Enter 时显示输出字符串,即“您要删除所有记录(y/n)”
  • 看看@niiraj874u的回答
  • 欢迎来到 Stack Overflow!如需帮助格式化您的帖子,请单击编辑器中的大橙色问号。此外,始终请务必阅读选择标签时出现的说明!

标签: java arraylist java.util.scanner


【解决方案1】:

我想这会对你有所帮助

Scanner input= new Scanner(System.in);
String readString = input.nextLine();
while(readString!=null) {
    System.out.println(readString);
    if (readString.equals(""))
        System.out.println("Read Enter Key.");
    if (input.hasNextLine())
        readString = input.nextLine();
    else
        readString = null;
}

【讨论】:

  • 看起来很像另一个答案,但程序流程有一些变化,所以我不会投票结束。
【解决方案2】:

你可以读取行,如果行是空白的,你可以假设它是输入键..就像下面的代码..

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
System.out.println(readString);
if (readString.equals(""))
    System.out.println("Enter Key pressed.");
if (scanner.hasNextLine())
    readString = scanner.nextLine();
else
    readString = null;

【讨论】:

  • 是的,这肯定会奏效。但是,如果用户不按 Enter,我也尝试通过参数获取输入。
  • 当用户按下回车键时会显示“你想删除所有记录(y/n)”
猜你喜欢
  • 2019-01-08
  • 1970-01-01
  • 2013-08-19
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多