0

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..

5
  • 2
    int can never be null. Never! Commented Jun 29, 2016 at 12:49
  • Scanner Class throws Exception on input mismatch instead null which an int can not be Commented Jun 29, 2016 at 12:51
  • This may be useful: stackoverflow.com/q/970029/423955 Java primitive types cannot be null. Only references to Objects can be null. Commented Jun 29, 2016 at 12:51
  • there is a hasNextInt() method for a purpose ... Commented Jun 29, 2016 at 12:53
  • Possible duplicate of Validating input using java.util.Scanner Commented Jun 29, 2016 at 12:55

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

9 Comments

Please be more precise: an int cannot be null; an Integer can; integer is not a thing in Java.
I did say integer not Integer and int is short for: integer.
@FelixRosén obviously it is; but by saying "integer", it is not clear whether you are referring to Integer (which can be null) or int (which cannot be null).
@FelixRosén yes. Integer usually refers to java.lang.Integer; integer is not a standard type in Java.
|
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.