test if a string is an integer?

D

dave

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.
 
M

Murray

dave said:
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
 
M

Murray

there is no such group as comp.lang.java.

I've heard several people mention this, yet comp.lang.java does seem to
exist. Do you mean it's now defunct and should not be used?
 
M

Michael N. Christoff

Roedy Green said:
there is no such group as comp.lang.java.

There is, its just not a 'core' group and hence not carried by all usenet
servers.



l8r, Mike N. Christoff
 
L

Liz

Murray said:
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.
 
C

Chris Dutton

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);
 
T

Tony Morris

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.
 
T

Tor Iver Wilhelmsen

Michael N. Christoff said:
There is, its just not a 'core' group and hence not carried by all usenet
servers.

It's a deprecated group, and therefore should not be "writable" by
well-behaved news servers.
 
R

Raymond DeCampo

Chris said:
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
 
L

lordy

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 :)
 
C

Chris Dutton

lordy said:
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+$
 
T

Tony Morris

Chris Dutton said:
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.
 
C

Carl Howells

Tony said:
You will never achieve perfection with a regex, raising the question of "why
bother?".

Careful with that word "never". I could create a regex to recognize
every legal decimal representation for a java int (32 bit, 2's
complement, signed), fairly easily. After all.. There are only a
finite number of possible values to check for.

Not that I'd do by enumerating all of them, as a regex based on that
would have at least 2^32 + 1 nodes in its internal automaton. But there
are simpler approaches that would work in a decent amount of memory. I
think I can get the version for the byte data type to at least be
reasonable:

^(0*(1(2([0-7])|[01]\d)|\d{1,2}))|(-0*(1(2([0-8])|[01]\d)|\d{1,2}))$

Note that for efficiency, all those () blocks should really be (?:)
blocks, but that makes it much harder to read. This was actually
tested, and actually works correctly.

Anyway, clearly, doing the same thing for short, int, or long isn't
harder, though the amount of typing does increase significantly. Doing
something like that for floating-point types would be more difficult,
but it's still obviously possible theoretically.

Of course... All that's just my reaction to the word "never". I
actually agree that regexes shouldn't be used to solve this kind of
problem. To paraphrase the advice: "The programmer had a problem.
Then he thought, 'Aha! I'll use a regex!' Then he had two problems."
 
D

Dimitri Maziuk

Tony Morris sez:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top