I've looked at similar questions and tried to follow the answers that solved the issues that others have had but putting the sc.next() or sc.nextLine() after the while loop causes it to go into an infinite loop.
The problem is if a user enters incorrect input (nothing or a number) multiple times before entering the correct info, I get empty lines. As shown in my output block, when I enter 1 for first name I have to enter it twice for it to output that it is the wrong format, then entering blank lines after that it won't read until I enter another character of some sort.
I know it has to do with nextInt() not reading the newline but how do I get it to work correctly in this method?
protected static void setFirstName(){
System.out.print("First Name: ");
while(sc.nextLine() == "" || sc.nextLine().isEmpty()){
System.out.println("Name is empty. Please Try again.\nFirst name:");
sc.nextLine();
}
while (sc.hasNextInt() || sc.hasNextDouble()) {
System.out.print("Incorrect Name format. Please Try again.\nFirst name: ");
sc.nextLine();
}
firstName = sc.nextLine();
firstName = Character.toUpperCase(firstName.charAt(0)) + firstName.substring(1);
}
Here is the output I get when I enter a number first and then blank returns:
First Name: 1
1
Incorrect Name format. Please Try again.
First name:
1
Incorrect Name format. Please Try again.
First name: Incorrect Name format. Please Try again.
First name: Incorrect Name format. Please Try again.
First name: Incorrect Name format. Please Try again.
First name: Incorrect Name format. Please Try again.
First name:
Here is the output I get when I enter a blank return first and then a number:
First Name:
Name is empty. Please Try again.
First name:
1
1
1
1
Incorrect Name format. Please Try again.
First name: