简体   繁体   中英

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?

The int userIn is inside the try-catch scope, and you can use it only inside the scope not outside.

You must declare it outside the try-catch brackets:

int userIn = 0;
try{

userIn = ....
}.....

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.

Try something like this

int userIn = x;   // where x could be some value that you're expecting the user will not enter it, you could Integer.MAX_VALUE

try{
    userIn = Integer.parseInt(in.next());
}

catch (NumberFormatException a){
    System.out.print("Problem");
}

This will cause and exception if the user entered anything than numbers because it will try to parse the user input String as a number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM