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

夙愿已清 提交于 2019-11-27 08:33:01

问题


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

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

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.

}

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.


回答1:


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;



回答2:


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


来源:https://stackoverflow.com/questions/23194290/how-to-capture-enter-key-using-scanner-as-console-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!