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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

is Integer???

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
How can check if the value I type on a textbox is an integer or not?

thank you.
 
Simple way:
Code:
String idText = "12";
int id = null;
try {
  id = Integer.parseInt(idText);
}
catch (NumberFormatException nfe) {
  // If Exception then it is not an int. 
  // Do Error Handling.   
}
// If no exception then it is an int
System.out.println(id);
 
Sorry, it should be:
Code:
int id;
I was originally going to use an Integer. Changed to int but forgot to take out the null assignment.

 
thanks. That was more or less what I was doing except I wasn't using the NumberFormatException. I thought java would have a function to test this like VB, it seems I was wrong :)
 
Hi,

There is also a isDigit() method but it is only for characters. Alternative solution would be (but i'd prefer use that NumberFormatException catching):

String s = "12";
if(isdigit(s))
{
System.out.println(s + " is digit.");
}
else
{
System.out.println(s + " is not digit.");
}

private boolean isdigit(String str_)
{
char[] c = str_.toCharArray();

for(int i=0; i<c.length; i++)
{
if(!Character.isDigit(c))
return false;
}
return true;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top