Wednesday 23 March 2016

regex - Java : scanner - I need to read alpha-numeric line including space/tab but not new-line



I am using java scanner to read input from System.in. I need to read alpha-numeric line including space/tab but not the new-line and should not allow empty input as well.



For example :



a new name



or



a-new-name-1


Here is my scanner:



Scanner reader = new Scanner(System.in);



I tried these ways:



String name = reader.nextLine();


or



String name = reader.next("^[A-Za-z0-9- ]+$");



or



name = reader.next("/^[a-z\\d\\-_\\s]+$/i");


For last 2 cases with input "a test name 1" , I had error:



Exception in thread "main" java.util.InputMismatchException

at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.next(Scanner.java:1418)
............


And when used reader.nextLine(),it's skips waiting for next input.For example:



For this part of the code:




System.out.println("Do you want to update audience name?[y/n]");
opt = reader.next().trim();

if( opt.equalsIgnoreCase("y") )
{
System.out.println("Enter audience name : ");
name = reader.nextLine();
}

System.out.println("Do you want to update audience description?[y/n]");

opt = reader.next().trim();

if( opt.equalsIgnoreCase("y") )
{
System.out.println("Enter audience description : ");
description = reader.nextLine();
}


I am seeing this:




Do you want to update audience name?[y/n]
y
Enter audience name :
Do you want to update audience description?[y/n]
y
Enter audience description :
Do you want to update audience rule?[y/n]



May I get any help here?


Answer



FOllow Jonny Henly's suggestion. Mixing up of reader.next and reader.nextLine was the problem.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...