问题描述
Validate if a given string is numeric.
Some examples:
"0"=>true
" 0.1 "=>true
"abc"=>false
"1 a"=>false
"2e10"=>true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
问题分析
这题我们可以用java自带的函数来判断,Double.valueOf(s)直接判断是不是数字,为了让函数能正常运行,用try catch方法来包裹函数。
要注意浮点数和double类型,最后不能出现f和d这样的符号。特别注意一下就好了,没什么很大的难度。
代码实现
public boolean isNumber(String s) {
try {
char c = s.charAt(s.length() - 1);
if (c == 'f' || c == 'F' || c == 'd' || c == 'D') return false;
Double.valueOf(s);
return true;
} catch (Exception e) {
return false;
}
}
网友评论