Having trouble with the getChoiceString method. If the user enters anything besides "y" or "n" an error message is suppose display. The problem is even if I type the correct response in the prompt it shows the error message.
//Ask user if they want to continue
choice = getChoiceString(sc, "Continue? (y/n): ", "y", "n");
System.out.println();
} //end while loop
} // end main method
// Method to make sure user doesn't leave continue prompt null
public static String getRequiredString(Scanner sc, String prompt)
{
String s;
// Flag to exit loop
boolean isValid = false;
// While loop to validate user input on continue prompt
while(!isValid){
System.out.print("\nContinue? (y/n): ");
s = sc.nextLine();
if (s.isEmpty())
System.out.print("Error! This entry is required. Try again.");
else
// Exit loop
isValid = true;
}
return prompt;
}
// Method to validate continue prompt input is either "y" or "n"
public static String getChoiceString(Scanner sc, String prompt, String s1, String s2){
String s = "";
boolean isValid = false;
while(!isValid)
{
s = getRequiredString(sc,prompt);
if (s1.equalsIgnoreCase("y"))
System.out.print("Error! Entry must be 'y' or 'n'. Try again:\n");
else
if (!s2.equalsIgnoreCase("n")) {
System.out.print("Error! Entry must be 'y' or 'n'. Try again:\n");
} else {
isValid = true;
}
}
return s;
}
Aucun commentaire:
Enregistrer un commentaire