In my program below I want the user to enter 3 letters only. My program detects a an incorrect input but does not continually prompt the user to enter the correct input. It instead moves on to the 2nd requested input if a number is entered instead of a letter for example.
My question is how can I make this program loop until the correct input is entered?
Also can my code be simplified? As I have the same conditions for input1 input2 and input3 is there a way to specify the conditions in a single statement rather than what I did?
public static void main(String[] args)
{
Scanner scnObj = new Scanner(System.in);
System.out.println("enter 3 letters");
String input1 = scnObj.nextLine();
if(!Pattern.compile("[a-zA-Z]*").matcher(input1).matches()){
System.out.println("try again.");
}
else {
System.out.println("enter the 2nd");
}
String input2 = scnObj.nextLine();
if(!Pattern.compile("[a-zA-Z]*").matcher(input2).matches()){
System.out.println("Please try again.");
}
else {
System.out.println("enter the 3rd");
}
String input3 = scnObj.nextLine();
if(!Pattern.compile("[a-zA-Z]*").matcher(input3).matches()){
System.out.println("try again.");
}
scnObj.close();
}
}