Tony Morris sez:
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
FVO "slight" heavily dependent on quality of the input: for
input string that are mostly not valid Java ints the slowdown
can be an order of magnitude, compared to the same number of
input strings that are mostly valid Java ints. (Note that
"integer" != "Java int": a number outside of 32-bit int range
is still a perfectly good integer.)
(It gets better when you get to floating-point numbers: last
I checked Double.parseDouble() didn't understand "1e-3" or
"+inf".)
To sum it up: there are two ways:
..parseXXX() actually converts string to number and comes
with exception overhead. You want to use it if you need to
convert the strings. You don't want to use when parsing huge
amounts of strings that are known to be mostly not Java
numbers.
Regexp and looking at the string character-by-character are
the same method, the only difference is performance of
regex match vs. that of your hand-rolled code. (And, of
course, quality of your code/regexp.) It does not convert
strings to numbers. It can recognize valid numbers that
are not "Java valid numbers".
Take your pick.
Dima
--
True courage comes from steadying yourself and forcing yourself to ssh into the
fscking thing yet again and not admitting that it doesn't care what it's done
to your life. -- "Hidden among the nodes" by ADB