By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,468 Members | 1,859 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,468 IT Pros & Developers. It's quick & easy.

test if a string is an integer?

P: n/a
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.
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.720 / Virus Database: 476 - Release Date: 7/14/04
Jul 17 '05 #1
Share this Question
Share on Google+
10 Replies


P: n/a

"dave" <go**********************@nowhere.com> wrote in message
news:FA******************@nwrdny02.gnilink.net...
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.


Try to perform Integer.parseInt(yourString) and if it throws a
NumberFormatException you'll know the string isn't a valid integer
Jul 17 '05 #2

P: n/a
"dave" <go**********************@nowhere.com> wrote in message
news:FA******************@nwrdny02.gnilink.net...
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.


Hand the String to parseInt and catch NumberFormatException.
see:
http://java.sun.com/j2se/1.4.2/docs/...va.lang.String)
--
Gary
Jul 17 '05 #3

P: n/a
Liz

"Murray" <pa***@SMAFFoffSPAMMER.optusnet.SPAMMAGE.com.au> wrote in message
news:6P****************@news-server.bigpond.net.au...

"dave" <go**********************@nowhere.com> wrote in message
news:FA******************@nwrdny02.gnilink.net...
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.


Try to perform Integer.parseInt(yourString) and if it throws a
NumberFormatException you'll know the string isn't a valid integer


Do you really mean integer? Or is a "number" ok, then you can use
Double.parseDouble(string); which will return a result for integers,
floats, and doubles.
Jul 17 '05 #4

P: n/a
As an alternative to the solution already provided...

import java.util.regex.*;

....

Pattern integerPattern = Pattern.compile("^\d*$");
Matcher matchesInteger = integerPattern.matcher(myString);
boolean isInteger = matchesInteger.matches();

or:

boolean isInteger = Pattern.matches("^\d*$", myString);
Jul 17 '05 #5

P: n/a
> 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/
Jul 17 '05 #6

P: n/a
Chris Dutton wrote:
As an alternative to the solution already provided...

import java.util.regex.*;

...

Pattern integerPattern = Pattern.compile("^\d*$");
Matcher matchesInteger = integerPattern.matcher(myString);
boolean isInteger = matchesInteger.matches();

or:

boolean isInteger = Pattern.matches("^\d*$", myString);


Note that this method is *not* equivalent to the other methods which use
Integer.parseInt(). This method will accept inputs that are outside the
range of a Java int, while Integer.parseInt() will not. Use whichever
one is appropriate for your application.

Also, I believe you forgot about the negative sign. :)

HTH,
Ray

--
XML is the programmer's duct tape.
Jul 17 '05 #7

P: n/a
Raymond DeCampo <rd******@spam.twcny.spam.rr.spam.com.spam> wrote in
news:sN*******************@twister.nyroc.rr.com:
Chris Dutton wrote:
As an alternative to the solution already provided...

import java.util.regex.*;

...

Pattern integerPattern = Pattern.compile("^\d*$");
Matcher matchesInteger = integerPattern.matcher(myString);
boolean isInteger = matchesInteger.matches();

or:

boolean isInteger = Pattern.matches("^\d*$", myString);
Note that this method is *not* equivalent to the other methods which

use Integer.parseInt(). This method will accept inputs that are outside the range of a Java int, while Integer.parseInt() will not. Use whichever
one is appropriate for your application.

Also, I believe you forgot about the negative sign. :)

It will also match the empty string so is a good example why one shouldnt
use tricks unless one is 37ETE HaX0r :)

--
Lordy
Jul 17 '05 #8

P: n/a
lordy wrote:
It will also match the empty string so is a good example why one shouldnt
use tricks unless one is 37ETE HaX0r :)


Yeah yeah... I never said it was perfect, but it is an alternative.
Maybe a pattern more like:

^-?\d+$
Jul 17 '05 #9

P: n/a

"Chris Dutton" <ru******@hotmail.com> wrote in message
news:Y3_Jc.44399$od7.18972@pd7tw3no...
lordy wrote:
It will also match the empty string so is a good example why one shouldnt use tricks unless one is 37ETE HaX0r :)


Yeah yeah... I never said it was perfect, but it is an alternative.
Maybe a pattern more like:

^-?\d+$


You will never achieve perfection with a regex, raising the question of "why
bother?".
After all, you will have to handle the cases that your regex misses (or the
ones that it doesn't depending on your proposed hack) negating the whole
purpose of attempting to check the validity of the data beforehand.

Declare to catch the NumberFormatException.
The Number subclasses *should* have had a 'isParsable' method or declared
NumberFormatException to be checked - the best workaround to this
unfortunate shortcoming of the core API is to explicitly catch the
NumberFormatException. Sad, but true.

--
Tony Morris
http://xdweb.net/~dibblego/
Jul 17 '05 #10

P: n/a
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
Jul 17 '05 #11

This discussion thread is closed

Replies have been disabled for this discussion.