473,782 Members | 2,448 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 199265

"dave" <go************ **********@nowh ere.com> wrote in message
news:FA******** **********@nwrd ny02.gnilink.ne t...
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.parseIn t(yourString) and if it throws a
NumberFormatExc eption you'll know the string isn't a valid integer
Jul 17 '05 #2
"dave" <go************ **********@nowh ere.com> wrote in message
news:FA******** **********@nwrd ny02.gnilink.ne t...
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 NumberFormatExc eption.
see:
http://java.sun.com/j2se/1.4.2/docs/...va.lang.String)
--
Gary
Jul 17 '05 #3
Liz

"Murray" <pa***@SMAFFoff SPAMMER.optusne t.SPAMMAGE.com. au> wrote in message
news:6P******** ********@news-server.bigpond. net.au...

"dave" <go************ **********@nowh ere.com> wrote in message
news:FA******** **********@nwrd ny02.gnilink.ne t...
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.parseIn t(yourString) and if it throws a
NumberFormatExc eption 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.parseDou ble(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(myStrin g);
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 RuntimeExceptio n, 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.parseIn t(i);
return true;
}
catch(NumberFor matException nfe)
{
return false;
}
}

Note that there is a slight performance penalty for doing this - the only
suitable alternative is to simply catch the RuntimeExceptio n 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(myStrin g);
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.parseIn t(). This method will accept inputs that are outside the
range of a Java int, while Integer.parseIn t() 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.s pam.com.spam> wrote in
news:sN******** ***********@twi ster.nyroc.rr.c om:
Chris Dutton wrote:
As an alternative to the solution already provided...

import java.util.regex .*;

...

Pattern integerPattern = Pattern.compile ("^\d*$");
Matcher matchesInteger = integerPattern. matcher(myStrin g);
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.parseIn t(). This method will accept inputs that are outside the range of a Java int, while Integer.parseIn t() 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******@hotma il.com> wrote in message
news:Y3_Jc.4439 9$od7.18972@pd7 tw3no...
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 NumberFormatExc eption.
The Number subclasses *should* have had a 'isParsable' method or declared
NumberFormatExc eption to be checked - the best workaround to this
unfortunate shortcoming of the core API is to explicitly catch the
NumberFormatExc eption. Sad, but true.

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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1560
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 same. Thanks.
3
8693
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 IsInteger() function ?
6
7002
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')); // PRINTS NOTHING print_r(strlen((int)1)); // PRINTS '1' Now I understand that in PHP, everything scalar is a string and can
4
2645
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 match is never returned. The string that I give to the regex is one that contains the entire contents of a text file. I'm using the multi-line option and I've also tried stripping out the VbCr
10
4939
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 == 16) /* and so on */ ); }
7
30214
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, Laura
5
3251
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" discount "*0.9". 10% discount, now I want calculate this with the price. The price is integer, and the discount must be a string, because of the */- how can I calculate them anyway ?
4
2790
by: smartic | last post by:
how to test string whether it contains special characters -------------------------------------------------------------------------------- please help dear experts on how to test string especially in username for example wheter it contains special charater and will return invalid ex for special characters (",',#,!,>,<,?) except any letters for other languages ?
0
9639
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9942
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8967
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7492
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6733
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4043
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2874
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.