Search code examples
javaswitch-statementtry-catch

Try catch and user input


This is a question for a homework assignment involving a try/catch block. For a try/catch I know that you place the code you want to test in the try block and then the code you want to happen in response to an exception in the catch block but how can i use it in this particular case?

The user enters a number which is stored in userIn but if he enters a letter or anything besides a number I want to catch it. The user entered number will be used in a switch statement after the try/catch.

Scanner in = new Scanner(System.in);

try{

int userIn = in.nextInt();

}

catch (InputMismatchException a){

    System.out.print("Problem");

}

switch(userIn){...

When I try to compile, it returns symbol not found, for the line number corresponding to the beginning of the switch statement, switch(userIn){. A few searches later I find that userIn cannot be seen outside the try block and this may be causing the error. How can I test userIn for correct input as well as have the switch statement see userIn after the try/catch?


Solution

  • Use something like:

    Scanner in = new Scanner(System.in);
    
    int userIn = -1;
    
    try {
        userIn = in.nextInt();
    }
    
    catch (InputMismatchException a) {
        System.out.print("Problem");
    }
    
    switch(userIn){
    case -1:
        //You didn't have a valid input
        break;
    

    By having something like -1 as the default value (it can be anything that you won't receive as input in the normal run, you can check if you had an exception or not. If all ints are valid, then use a boolean flag which you can set in the try-catch blocks.