Friday, 14 February 2014

Java: Check if a string contains only digits

Following methods checks if the string contains only numbers

private boolean parseInt(String str)
{

try
{
Integer.parseInt(str);
                                return true
}
catch (Exception e)
{
new MessageDialog("Error", "Numeric fields should contain digits", JOptionPane.ERROR_MESSAGE);
                               return false;
}

}


Following method checks if the string contains numbers then returns a number otherwise returns 0


private int parseInt(String str)
{
int number = 0;
try
{
number = Integer.parseInt(str);
}
catch (Exception e)
{
new MessageDialog("Error", "Numeric fields should contain digits: " + str, JOptionPane.ERROR_MESSAGE);
}
return number;
}


Another simple way of checking if a string contains only digits is using regular expression

String regex = "\\d+";
Where the + means "one or more" and \d stands for "digit".
Note: the "double slash" gives only one slash. "\\d" gives you: \d
private boolean isDigit(String data)
{
boolean isDigit = false;
String regex = "\\d+";
isDigit = data.matches(regex);
return isDigit;
}

No comments:

Post a Comment