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

99 views Asked by At

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

3

There are 3 answers

2
Davide Lorenzo MARINO On BEST ANSWER

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.

0
Neeraj Jain On

The problem now is, that if I enter an integer, it won't throw anything.

No the problem is you thinking it's an integer , it's actually String .

String s=1; //Gives Compilation Error 

while

 String s="1"; // will not give any Error/Exception and this is your case

User will provide inputs until it met your Expected Input List , something like this :

List<String> expectedInputs=Arrays.asList("A","B","C","D");
String input=takeInputFromUser();
if(expectedInputs.contains(input)){
     //doWhatever you want to do 
}else{
     // throw any Exception
}
1
friendlyBug On

I recommend you to use regex in this case

try {
    answer = sc.nextLine().toUpperCase();
    invalidInput = !answer.matches("[ABC]");                
} catch(InputMismatchException e){
    System.out.println("Enter a letter please");
    invalidInput = true;
}