简体   繁体   中英

Java ParseInt() - Catching Strings with a leading zero

Java's ParseInt method will happily parse decimal values supplied with a leading zero without throwing an exception, stripping the zero:

int value = Integer.parseInt("050", 10);

will result in the integer value 50.

But, I have an application requiring a string such as this to be rejected as invalid input. My solution to the problem so far has been to convert the parsed integer back to a string, and compare the lengths of original/parsed strings to see if any character has been stripped, eg:

String original = "050";
value  = Integer.parseInt( "050", 10);
String parsed = Integer.toString(value);
if (original.length() != parsed.length()) {
    System.exit(1);
}

Which works fine, but feels a little hacky. Are there better ways of detecting and handling a leading zero?

Check if the first character is 0 :

if (original.charAt(0)=='0')

or

if (original.startsWith("0"))

If the String starts with a 0, you don't want to call parseInt at all.

I think that comparing a single character is more efficient than using regular expressions.

you could work with regex and check if it has a leading 0

you could just write

After seeing your comment about leading whitespaces beeing allowed you could use:

if(original.matches(".\\s0.*[1-9]")) // Wrong number with leading zeros

This way a 00000 would still be a zero, if it´s valid

As you get a string input you can use the method String.charAt(int) to check for explicit characters. However, when you are just using input.charAt(0) the user could avoid the leading zero with a space.

What I would suggest to do:

String decimalChars = "123456789";

boolean reject = true, hasZeros = false;
for (int i = 0; i < input.length; i++) {
    if (input.charAt(i) == '0') { // or other chars you don't want
        hasZeros = true;
        reject = false;
    } else if (decimalChars.contains(input.charAt(i)) {
           if (hasZeros) {
               reject = true;
            } else {
                reject = false;
            }
            break;
        }
    }
}

Using that you can do whatever you want to reject wrong inputs by checking reject . The code will break when it finds a character which is in the decimalChars array. reject will be true if it found a zero before, otherwise it'll be false. This code also allows spaces at the beginning and doesn't reject an input like 0000 . Empty strings will be rejected as well, because reject initializes with true.

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM