would you be so kind and help me please? Im doing a simple quiz game, during the game the user is asked to enter his answer. Its either A,B or C. i would like to have this covered with try/catch exceptions...
What I want this code to do, is to throw exception (force the user the enter the answer again) whenever he will enter something else than a String. here is the part of a code
Scanner sc = new Scanner(System.in);
String answer = "";
boolean invalidInput = true;
while(invalidInput){
try {
answer = sc.nextLine().toUpperCase();
invalidInput = false;
}
catch(InputMismatchException e){
System.out.println("Enter a letter please");
invalidInput = true;
}
}
The problem now is, that if I enter an integer, it won't throw anything.
Thanks
Simply throw an
InputMismatchException
if the data are not as you expected.Note that is not necessary to throw an Exception for this kind of controls. You can handle the error message directly in the if code.