Click to See Complete Forum and Search --> : how to test an integer?


Monika
September 18th, 2000, 07:06 AM
Hi,
I have a textbox in html. I am using a post method in it. When the value is recieved by the servlet, I want to test whether the value recieved from the textbox is a number or not.

Integer.parseInt(request.getParameter("textbex1"))
would give an error if the user has not entered a valid number.

Does anybody know the solution?
I will be grateful for the solution

Thanks in advance.
Monika

dogbear
September 18th, 2000, 08:36 AM
Monika,

You are correct in using the Integer.parseInt() method. To see if the String you passed it is a number, use the throw and catch exception handling for this method.

In other words:
// the integer
int number = 0;
// the string
String theString = "Two";
// the try block
try {
// parse the string and store in number
number = Integer.parseInt(theString);
}catch(java.lang.NumberFormatException e) {
// this code is executed if there was an error parsing the String
System.out.println("The String is not a number!");
}


Hope this helps!

Regards,

dogBear

PS Please Rate this Response!!!!

Monika
September 18th, 2000, 11:08 PM
Hi,
Thanks a lot for your reply.
But I don't want to throw an exception. I just want to test if it is number or not. The solution could be in java or javascript.
Bye,
Monika

dogbear
September 19th, 2000, 03:33 AM
Monika,

If you don't want to throw an exception, then simply test each character in the String, like so:

// the String holding the text
String theNumber = "25";
// the sentinel
boolean isANumber = true;
// loop through each character in the String
// notice that we're testing for two things:
// 1) index remains in bounds
// 2) isANumber remains true
for ( int index = 0 ; index < theNumber.length() && isANumber ; index++ )
if ( theNumber.charAt(index) < '0' || theNumber.charAt(index) > '9' )
isANumber = false;

// do the result printout...
if ( isANumber )
System.out.println("This is a number!");
else
System.out.println("This is NOT a number!");



Is this more what you're looking for?

Regards,

dogBear

PS Please Rate this Response!!!!