A very simple question. I use the traditional check-every-character way.
1. if the character is '-' but is not at the beginning of the string, return false;
2. else if there are more than one dots in the string, return false;
3. else if other characters are not digits, return false.
public class CheckNumber {
public boolean isNumber(String s)
{
if (s == null || s.length() == 0)
return false;
int dot = 0;
for (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == '-')
{
if (i != 0)
//System.out.println("-");
return false;
}
else if (s.charAt(i) == '.')
{
if (dot > 0 || i == 0 || i == s.length() - 1)
{
//System.out.println("*");
return false;
}
dot++;
}
else if(!Character.isDigit(s.charAt(i)))
{
//System.out.println(i + "isDigit");
return false;
}
}
return true;
}
}
There are other simpler ways that use regex.
public boolean isNumber2(String str) {
if(str==null) return false;
return str.split("(^-)?\\d+(\\.)*\\d*").length == 0;
}
^: beginning of the string
(-)? the hyphen appear one or no times
\d: digits
(\\.): the period appears one or no times
No comments:
Post a Comment