Reputation: 103
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.
Upvotes: 1
Views: 23959
Reputation: 11
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;
}
Upvotes: 1
Reputation: 2208
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;
Upvotes: 3