[Solved] Why does the java accepts integer with a ‘+’ sign and how to not accept integer input with a ‘+’ sign


You are reading an int using Scanner.nextInt(): as described in the documentation, this uses Integer.parseInt to read the number; and that method explicitly states that it accepts a leading + sign:

The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign ‘-‘ (‘\u002D’) to indicate a negative value or an ASCII plus sign ‘+’ (‘\u002B’) to indicate a positive value

And once you’ve read that number, there’s no way to distinguish the fact that you entered 123 or +123, because there’s no difference in the value. So, you’ve lost the + even before you convert the int to a String.

To capture this, you need to read the String first, and convert that to an int:

String sAmount= scan.next();
nAmount = Integer.parseInt(sAmount);

This preserves the + sign in sAmount, because there is no reason to strip it away. Note that it will fail if sAmount can’t actually be parsed as an int.

0

solved Why does the java accepts integer with a ‘+’ sign and how to not accept integer input with a ‘+’ sign