473,394 Members | 1,735 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

test if a string is an integer?

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
10 199193

"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
"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
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
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
> 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
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
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
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

"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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: codefixer | last post by:
Hi, Does anybody know how to test string library functions ? I have already gone through "gcc-3.4.1/gcc/testsuite/gcc.c-torture/execute" I want to know if their is any other way to test the...
3
by: Rob | last post by:
I have a 3 character string that I want to test to see if it is a positive integer... I could test that each individual character is >=0 and <=9... is there a better way ? Is there an...
6
by: comp.lang.php | last post by:
I'm involved in a rather nasty debate involving a strange issue (whereby the exasperated tell me to RTFM even after my having done so), where this is insanely possible: print_r(is_int('1'));...
4
by: Chris | last post by:
Hi Everyone, I am using a regex to check for a string. When all the file contains is my test string the regex returns a match, but when I embed the test string in the middle of a text file a...
10
by: David T. Ashley | last post by:
What is the most economical test in 'C' for "integer is a power of 2"? For example, something better than: void is_2_pow(int arg) { return((x == 1) || (x == 2) || (x == 4) || (x == 8) || (x...
7
by: laura | last post by:
Hi, I have a variable of type double. I need to know if there is an integer number store there. How can I test that ? I also have a default precision for doing this operation. Many thanks,...
5
by: zivon | last post by:
Hello everyone ! I made a price calculator for a guest house. I have diffrent sale campaigns, all the time, I made a table with campaign name and discount, for example: name "pensioners"...
4
by: smartic | last post by:
how to test string whether it contains special characters -------------------------------------------------------------------------------- please help dear experts on how to test string...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.