public class E20CheckStringForNumeric {
private static int strIndex = 0;
public static boolean isNumeric(char[] str){
//两种模式A[.[B]][e|E C]、.B[e|E C]
if (str == null)
return false;
boolean numeric = isIntegerNumeric(str);
if (strIndex < str.length && str[strIndex] == '.'){
strIndex ++;
numeric = isNonnegativeNumeric(str) || numeric;
}
if (strIndex < str.length && (str[strIndex] == 'e' || str[strIndex] == 'E')) {
strIndex ++;
numeric = numeric && isIntegerNumeric(str);
}
boolean isEnd = strIndex == str.length;
//使用完重置静态变量
strIndex = 0;
return numeric && isEnd;
}
private static boolean isIntegerNumeric(char[] str){
//用于验证B部分
if (strIndex < str.length && (str[strIndex] == '+' || str[strIndex] == '-'))
strIndex ++;
return isNonnegativeNumeric(str);
}
private static boolean isNonnegativeNumeric(char[] str){
//用于验证A、C部分
int index = strIndex;
while (strIndex < str.length && str[strIndex] >= '0' && str[strIndex] <= '9')
strIndex ++;
return strIndex > index;
}
//测试用例
public static void main(String[] args){
char[] number1 = {'1', '.', '3', 'E', '+', '5'};
char[] number2 = {'1', '.', '+', 'E', '+', '5'};
System.out.println(E20CheckStringForNumeric.isNumeric(number1));
System.out.println(E20CheckStringForNumeric.isNumeric(number2));
}
}
表示数值的字符串(Java实现)
最新推荐文章于 2023-06-02 20:04:03 发布