My main issue is, while passing "hello" the output is java.util.InputMismatchException. But while passing (2147483648) long in int type the output is= java.util.InputMismatchException: For input string: "2147483648". I want to know why is it printing extra content.
That is a different question to what you were originally asking, but I will answer anyway.
The reason you are getting "extra content" as in:
java.util.InputMismatchException: For input string: "2147483648"
is that you are printing the exception like this:
System.out.println(e);
This calls toString() on the exception object and prints it. The toString() method for a typical exception is roughly equivalent to this:
public String toString() {
return e.getClass().getName() + ": " + e.getMessage();
}
If you don't want the exception name, just print the exception message:
System.out.println(e.getMessage());
If you what the exception name without the message:
System.out.println(e.getClass().getName());
And so on.
(IMO, none of these are the kind of message you should be showing to users. They don't explain the problem in terms that a user would understand!)
I want the output to be same for both Hello and 2147483648.
It will be, I think. For "Hello", the output will be:
java.util.InputMismatchException: For input string: "Hello"
Finally, if you actually want an intelligible error message, you will need to make more extensive modifications to the code. Unfortunately, neither nextInt() or Integer.parseInt(...) give exception messages that explains:
- that an
int is expected, and
- why the input string is not an acceptable
int value.
Addressing this in a general way is difficult. The Scanner.nextInt method doesn't "understand" what the number means in the context of the call. In the particular case, you could call sc.next() to get the string, and manually test if it is an out-of-range integer or something else. But be aware that the Scanner.nextInt uses locale-sensitive parsing.