Java ParseInt() - Catching Strings with a leading zero
Asked Answered
C

3

5

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?

Chaplin answered 5/2, 2015 at 13:6 Comment(9)
Can't you use regex to check for leading 0s?Unitary
Does it have to account for more than one leading 0? e.g. 0050. Furthermore, what about leading spaces or anything like that?Baerl
Leading spaces are allowed in my case, but one or more leading zeroes 0050 should be caughtChaplin
possible duplicate of Javascript parseInt() with leading zerosBojorquez
@ShawnBush this is a substantially different question as far as I can tell.Baerl
@ChrisSprague thanks, I did read around before posting (It's my first question ever...) and the Javascript questions tend to regard the default radix of base-8 causing weird behaviour with leading zeroes. Java defaults to decimal anyway.Chaplin
@Chaplin Right. I was addressing another commenter who flagged this as a duplicate question. Your question is about a parseInt issue in Java where the other one is a different issue, and it's in Javascript... (so the duplicate reported is incorrect.)Baerl
@ChrisSprague understood - I was just saying thanksChaplin
@Chaplin ah. no problem then (:Baerl
B
12

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.

Bursiform answered 5/2, 2015 at 13:10 Comment(3)
this should be the answer, regex is to heavy.Pickar
So simple. Thanks for this - I'm new to Java and only just beginning to realise that things like startsWith actually exist...Chaplin
But this wont catch the leading whitespace beeing noticed in a comment anymore, and should be trimmed.Moorwort
M
2

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

Moorwort answered 5/2, 2015 at 13:11 Comment(0)
M
0

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!

Moshe answered 5/2, 2015 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.