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?

9
  • 4
    Can't you use regex to check for leading 0s? Commented Feb 5, 2015 at 13:09
  • Does it have to account for more than one leading 0? e.g. 0050. Furthermore, what about leading spaces or anything like that? Commented Feb 5, 2015 at 13:09
  • Leading spaces are allowed in my case, but one or more leading zeroes 0050 should be caught Commented Feb 5, 2015 at 13:11
  • possible duplicate of Javascript parseInt() with leading zeros Commented Feb 5, 2015 at 13:12
  • @ShawnBush this is a substantially different question as far as I can tell. Commented Feb 5, 2015 at 13:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

this should be the answer, regex is to heavy.
So simple. Thanks for this - I'm new to Java and only just beginning to realise that things like startsWith actually exist...
But this wont catch the leading whitespace beeing noticed in a comment anymore, and should be trimmed.
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

Comments

-1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.