Re: how to test an integer?
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!!!!
Re: how to test an integer?
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
Re: how to test an integer?
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!!!!