I want my program to only accept string and prompt a message if the user input is invalid.
import java.util.Scanner;
public class Details{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String lastname;
String firstname;
String middlename;
System.out.print("Enter Number of passenger : ");
int passenger = input.nextInt();
for(int x = 0 ; x < passenger ; x++){
do{
System.out.print("\nEnter Lastname :");
lastname = input.nextLine().trim();
if(lastname.equals("") || lastname.equals(" "))
{
System.out.print("\nEnter Neccessary Details");
}
} while(lastname.isEmpty());
do{
System.out.print("\nEnter Firstname : ");
firstname = input.nextLine();
if(firstname.equals("") || firstname.equals(" "))
{
System.out.print("\nEnter Neccessary Details");
}
} while(firstname.isEmpty());
do{
System.out.print("\nEnter Firstname : ");
middlename = input.nextLine();
if(middlename.equals("") || middlename.equals(" "))
{
System.out.print("\nEnter Neccessary Details");
}
}while(middlename.isEmpty());
}//end of forloop
}
}
i already try this code, at first it works but it shows logical error in the long run. And give me an output something like this.
sample output
Enter Firstname : // the problem is, it seems has already have an input
Enter Neccessary Details
Enter Firstname :
so how can i fix this? is there an alternative way to validate string input? please keep it simple i am just a beginner thanks