1

Consider this, if userChoice is not an integer:

Scanner choice = new Scanner(System.in);
int userChoice = choice.nextInt();
if(....){
    .... //not important
}
else if(userChoice == null){
    System.out.println("wrong input..");
    System.exit(0);
}

Why cant I do this? And instead have to do:

import java.util.InputMismatchException;

..... //bunch of code

Scanner choice = new Scanner(System.in);
    int userChoice;
    try {
        userChoise = choice.nextInt();
        if(...){
          ..... //not important
        }
    }
    catch(InputMismatchException e) {
        System.out.println("wrong input..");
        System.exit(0);
    }

I thought it was so that if I inputed, say, a char when it expected an int it would simply return null. So if I checked for null then it would be sufficient. So what am I missing/not understading?

So this is not a question regarding the Scanner library. If you want to boil it down it was that I did not know that a integer could not be null. So the user who thought that this was duplicated, it might be. But it is certainly not a duplicate to the post that you suggested..

Felix Rosén
  • 1,391
  • 1
  • 17
  • 33

2 Answers2

4

An int cannot be null. It can be any number in its range.

Shiro
  • 2,510
  • 2
  • 14
  • 32
0

Apart from the fact that you need to use Integer instead of int if you want to return null, it is not advisable. The main reason is that checking an output for null is easily forgotten and may lead to error situations much later in the program.

An exception, though, has to be catched or it climbs up the stack. Exceptions make it much easier to find out where an error happens (if they have proper content, they also say why it happened).

J Fabian Meier
  • 26,766
  • 8
  • 52
  • 98