表示数值的字符串(Java实现)


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));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值