Re: test if a string is an integer?
From: Tony Morris (not_at_telling.you)
Date: 07/16/04
- Next message: thufir.hawat_at_mail.com: "Re: what is a stack"
- Previous message: Tony Morris: "Re: String Arrays and Equality"
- In reply to: dave: "test if a string is an integer?"
- Next in thread: Dimitri Maziuk: "Re: test if a string is an integer?"
- Reply: Dimitri Maziuk: "Re: test if a string is an integer?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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/
- Next message: thufir.hawat_at_mail.com: "Re: what is a stack"
- Previous message: Tony Morris: "Re: String Arrays and Equality"
- In reply to: dave: "test if a string is an integer?"
- Next in thread: Dimitri Maziuk: "Re: test if a string is an integer?"
- Reply: Dimitri Maziuk: "Re: test if a string is an integer?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|