Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to check if a string is numbers? 2

Status
Not open for further replies.

Petal

Programmer
Jun 8, 2001
56
NO
I have a String test that I will make sure that only are numbers.

How do I do that?

 
Do this:
Code:
String test = "5";
boolean isNumber = false;
try {
   int i = Integer.parseInt(test);
   /* If you get here it is a number */
   isNumber = true;
}
catch (NumberFormatException) {
   isNumber = false;
}

if (isNumber) {
System.out.println(test + " is a valid number.");
}
else {
System.out.println(test + " is not a valid number.");
}
Wushutwist
 
I know there are people who prefer not to use try catch for such checkings so here is another example (although not as good in terms of memory wise)

String abc = "hello2";
int i=0;
for (i=0;i<abc.length();i++)
{
if (Character.isDigit(abc.charAt(i)))
break;
}
if (i < abc.length())
System.out.println(&quot;Invalid String.&quot;);
else
System.out.println(&quot;Valid String.&quot;);

Regards,
Leon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top