简体   繁体   English

如何使用扫描仪作为控制台输入来捕获Enter键?

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

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. 现在,情况2可以正常工作。 However, for Case 1, I want param value to be null when user presses enter. 但是,对于情况1,我希望当用户按下Enter键时param值为null。 I will then pass param as a null value to my remove function and delete all the students in the array list. 然后,我会将param作为空值传递给我的remove函数,并删除数组列表中的所有学生。

list1.clear();

Please help me in knowing how to get this enter key. 请帮助我了解如何获取此回车键。

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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM