Re: test if a string is an integer?

From: Tony Morris (not_at_telling.you)
Date: 07/16/04


Date: Fri, 16 Jul 2004 05:01:41 GMT


> I am reading input from a form. I want to validate the input by making
sure
> that the string is actually an integer. How would I do this? Do i need to
> convert it to a character array and break down each character and test it?
> or is there an easier way? Thanks.

This question has been asked many times.
You'll receive answers ranging from checking that each char is between '0'
and '9' through to the use of regular expressions.
All of these suggestions are severely flawed, offering no benefit, and in
most cases creating a hindrance (i.e. not neutral side-effects).

The reason that these suggestions are attempted is because nobody (assuming
everybody knows what they are doing) likes catching a RuntimeException, and
especially not for the purpose of control flow. There is no suitable
alternative.

If it really bothers you (as it does me), encapsulate the "brokenness" in a
single method:

public boolean isParsableToInt(String i)
{
    try
    {
        Integer.parseInt(i);
        return true;
    }
    catch(NumberFormatException nfe)
    {
        return false;
    }
}

Note that there is a slight performance penalty for doing this - the only
suitable alternative is to simply catch the RuntimeException each time an
attempt to parse is made.

-- 
Tony Morris
http://xdweb.net/~dibblego/


Relevant Pages

  • Re: test if a string is an integer?
    ... > I am reading input from a form. ... > that the string is actually an integer. ... > convert it to a character array and break down each character and test it? ... everybody knows what they are doing) likes catching a RuntimeException, ...
    (comp.lang.java)
  • Re: test if a string is an integer?
    ... >> I am reading input from a form. ... I want to validate the input by making ... >> that the string is actually an integer. ... >> convert it to a character array and break down each character and test ...
    (comp.lang.java)
  • Re: test if a string is an integer?
    ... >> I am reading input from a form. ... I want to validate the input by making ... >> that the string is actually an integer. ... >> convert it to a character array and break down each character and test ...
    (comp.lang.java.programmer)
  • Re: test if a string is an integer?
    ... > I am reading input from a form. ... I want to validate the input by making ... > convert it to a character array and break down each character and test it? ... Hand the String to parseInt and catch NumberFormatException. ...
    (comp.lang.java)
  • Re: test if a string is an integer?
    ... > I am reading input from a form. ... I want to validate the input by making ... > convert it to a character array and break down each character and test it? ... NumberFormatException you'll know the string isn't a valid integer ...
    (comp.lang.java.programmer)