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);
f_name = sc.next().toUpperCase();after the loop?123456) it will go on infinite loopsc.next()from inside the loop.