Search code examples
javastringexceptionletter

How do I read nothing else but a String using exceptions?


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


Solution

  • Simply throw an InputMismatchException if the data are not as you expected.

    Scanner sc = new Scanner(System.in);
    String answer = "";
    boolean invalidInput = true;    
    while(invalidInput){
        try {
            answer = sc.nextLine().toUpperCase();
            if (!answer.equals("A") && !answer.equals("B") && !answer.equals("C")) {
                throw new InputMismatchException();
            } 
            invalidInput = false;
        } catch (InputMismatchException e) {
            System.out.println("Enter a letter please");
            invalidInput = true;
        }
    }  
    

    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.