How to capture non-integers in this Java program

1.3k views Asked by At

How do I add a try-catch piece of code to stop someone from entering chars or, as a matter of fact, anything other than an int from 1 - 5?

boolean valid;
int option = 0;

do {
    Scanner in = new Scanner(System.in); // need try catch
    menu();
    System.out.println("\n");
    option = in.nextInt();

    valid = option > 0 && option < 6; // try / catch needed around here?

} while(!valid); // stop chars and strings being entered
// I want to stop the user entering anything other than an int 1-5
3

There are 3 answers

0
Sheetal Mohan Sharma On

Why not read the token as a string and use Integer.parseInt(), ignoring tokens that cannot be parsed as an integer. If not then handle it

2
Skaros Ilias On

if you need that number to check which option the user entered you dont need to do that. all you have to do is change the option variable from int to String and your if statements from
if(option==1) to if(option.equals("1"))

if you are going to need real ints for real mathematical equations then Sheetals answer will be more appropriate, but for a menu input, Strings are just fine.


dont forget that you can have String comparison with that contain numbers "1"<"2" is true

0
Arun Kumar On

Use string to enter the choice and then parse it using Integer.parseInt() function.

Scanner in = new Scanner(System.in);    
String choice = in.next();
try{
   int intChoice = Integer.parseInt(choice);
   if(choice > 5){
      throw new Exception("Can't be more than 5");
   }
}catch(Exception e){
   System.out.println(e.printStackTrace);
}