kristintirin kristintirin - 1 month ago 21
Java Question

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

Why does the java accepts integer with a '+' sign and how to not accept integer input with a '+' sign. Please help! Thanks in advance

nAmount= scan.nextInt();
String sAmount = Integer.toString(nAmount);
//ON THIS LINE, MY PROG SHOULD NOT ACCEPT INTEGERS WITH "+" SIGN
if (sAmount.contains("+")) {
System.out.println("金額に文字が入力されています。");
} else if (nAmount<=0) {
System.out.println("金額は0円以上で入力してください。");
} else if (nAmount>999999) {
System.out.println("金額は999,999円以下で入力してください。");
} else nAFlag =1;

Sample Output :
Input > 100 (Accepted)
Input > -100 (Not Accepted because of the constrain input is less than 0)
Input > +100 (IT SHOULD NOT BE ACCEPTED BECAUSE IT CONTAINS A SYMBOL)

Answer

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, when you convert the int to a String, you have already lost the +.

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.

Comments