+ 2
I'm trying to use the try-catch to handle user's input exception. Can someone please help me to figure out why it doesn't work?
Scanner usPick = new Scanner(System.in); try { int pick = usPick.nextInt(); //user pick } catch (InputMismatchException e) { System.out.println("Input Error"); } https://code.sololearn.com/cZhc60SBIiEC/?ref=app
2 ответов
+ 4
That code looks fine to me.
You may be having an issue with the scope of the variable.
Example fix/
int pick;
// enlarging the variables scope
try {
pick = usPick.nextInt();
}
catch(....){
// fail
}
switch (pick){
case 1:
// do stuff with pick
break;
}
Remember if you declare something inside a block, the block is the variables scope.
Example/
if (condition){
int x = 15;
// X can be accessed in here
}
// X cannot be accessed out here
You can also place the switch case that deals with the variable inside the try block.
+ 2
Thanks a lot for your comment!
I think I managed to solve it, you're welcome to check it up :)