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

问题描述:

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

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

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

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

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

Case 2. removestudent student1 removes students1 from array list.

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 作为空值传递给我的 remove 函数并删除数组列表中的所有学生.

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.

list1.clear();

请帮助我知道如何获得这个回车键.

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

你可以读取 line,如果 line 是空的,你可以假设它是 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;