题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、“0123"及”-1E-16"都表示数值,但"12e"、“1a3.14”、“1.2.3”、"±5"及"12e+5.4"都不是。
解答:
class Solution {
public boolean isNumber(String s) {
//利用异常来进行判断是否可以表示数值
try {
if(s.endsWith("f")||s.endsWith("d")||s.endsWith("F")||s.endsWith("D")){
throw new NumberFormatException();
}
Float.parseFloat(s);
return true;
} catch (Exception e) {
return false;
}
}
}