+ 2

Java, If Scanner Input == letter?

I have a question. For example: I'm asking for the age of a person by using a scanner. And putting the input in an int (For example: x). With an if statement I'm checking if the int x is smaller than 16, then he's not allowed to play. But now: when someone inputs a letter like abcdefg..... im getting an exception. I know why, because I'm asking for a number without validating if the person actually inputs one. So when he puts in a letter, its not a number and I'm getting an exception. Any way to catch the execption and asking the person to put in a number and not a letter? I'm using the SCANNERNAME.nextInt() method. Thanks for the help.

2nd Apr 2018, 1:12 PM
TheSchebbi
TheSchebbi - avatar
4 odpowiedzi
+ 1
have you tried putting it in a while loop and catching the exception? if you catch an exception maybe offer a print output suggesting to enter a number and then letting the loop go back to reenter a number. if no exception is thrown, let them out of the loop while { try { SCANNERNAME.nextint(); break; } catch (Exception e) { System.out.println("Enter a number"); continue; } } something like that
2nd Apr 2018, 1:25 PM
LordHill
LordHill - avatar
+ 1
Thanks :)
2nd Apr 2018, 2:09 PM
TheSchebbi
TheSchebbi - avatar
0
You can use a try catch statement. It would look something like this: try{ //line that throws exception (in your case scanner.nextInt()) }catch (Exception e){ //handle exception (re-prompt user for input) } You can also put your try/catch in a while loop until input is valid like this: boolean valid; While(!valid){ try{ //statement valid = true; }catch (Exception e){ //handle exception } }
2nd Apr 2018, 1:30 PM
Justin Hinkle
Justin Hinkle - avatar
0
You can catch exception using :- try { int input = scannerName.nextInt(); // remaining logic } catch (InputMismatchException e) { System.out.println("uh oh"); } or take the advantage of scanner class pre-existing function :- if(scannerName.hasNextInt()){ //Input is integer } else { //input is not an integer }
2nd Apr 2018, 8:30 PM
SatyaJit Pradhan
SatyaJit Pradhan - avatar