Sunday, February 11, 2018

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?

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...