0

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);
4
  • 2
    How about adding f_name = sc.next().toUpperCase(); after the loop? Commented Apr 22, 2021 at 10:40
  • Thanks for you answer @khelwood... It works great if the input is valid. If its not valid (e.g. 123456) it will go on infinite loop Commented Apr 22, 2021 at 10:42
  • 1
    I didn't say remove sc.next() from inside the loop. Commented Apr 22, 2021 at 10:44
  • oops! Works fine now thanks a lot :D Commented Apr 22, 2021 at 10:52

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.