programming_ritual
programming_ritual

Reputation: 188

How to use java scanner with string validation?

I have the following code:

String f_name = "";
System.out.println(ANSI_PURPLE + "What is your first name?");
System.out.print(ANSI_RESET + " Type your name here (use only latin characters) > ");

while(!sc.hasNext("[A-Za-z]*")) {
    System.out.println(ANSI_RED + " ERROR: Invalid option! ");
    System.out.print(ANSI_RESET + " Type your name here (use only latin characters) > ");
    f_name = sc.next().toUpperCase();
}


System.out.println("First Name = " + f_name);

The issue with the above code is that it would store what has previously added.

for example:

What is your first name?
 Type your name here (use only latin characters) > 123
 ERROR: Invalid option! 
 Type your name here (use only latin characters) > c
First Name = 123

How to fix so that the validation of latin characters will still work, redirect the user to same question if there is a mistake and store the correct value?


CORRECT ANSWER TO MY QUESTION:

...
while(!sc.hasNext("[A-Za-z]*")) {
    System.out.println(ANSI_RED + " ERROR: Invalid option! ");
    System.out.print(ANSI_RESET + " Type your name here (use only latin characters) > ");
    sc.next();
}

f_name = sc.next().toUpperCase();
System.out.println("First Name = " + f_name);

Upvotes: 0

Views: 278

Answers (1)

khelwood
khelwood

Reputation: 59240

When sc.hasNext("[A-Za-z]*") returns true, that means the next input you read will be the one you want. So you need to read f_name in after the loop ends.

You still need sc.next() inside the loop to move past bad input; otherwise you will have an infinite loop.

By the way, perhaps you want to use + instead of * in your regular expression. * means "zero or more", and + means "one or more". I assume you want one or more characters to be input.

while (!sc.hasNext("[A-Za-z]+")) {
    System.out.println(ANSI_RED + " ERROR: Invalid option!");
    System.out.print(ANSI_RESET + " Type your name here (use only latin characters) > ");
    sc.next();
}

String f_name = sc.next().toUpperCase();

Upvotes: 1

Related Questions