Java 如何捕获回车键,使用扫描仪作为控制台输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23194290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:16:13  来源:igfitidea点击:

How to capture enter key, using scanner as console input?

javaarraylistjava.util.scanner

提问by MrCoder

I want to capture enter character in console. I am inputting 2 strings.

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

Case 1. removestudent(pressing enter) removes all the students from array list.

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

Case 2. removestudent student1 removes students1 from array list.

案例 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.

}

Now the case 2 works fine. However, for Case 1, I want param value to be null when user presses enter. I will then pass param as a null value to my remove function and delete all the students in the array list.

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

list1.clear();

Please help me in knowing how to get this enter key.

请帮助我知道如何获得这个输入键。

回答by niiraj874u

You can read line and if line is blank, You can assume it is enter key.. like below code..

您可以阅读行,如果行为空白,您可以假设它是输入键..如下代码..

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;

回答by Hamed Refaat

I think this will help you

我想这会帮助你

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;
}