2021-07-12 将string转int

private static int stringToInt(String nums){
        if(null == nums || nums.length()<2){
            if(nums.length()==1 && (nums.codePointAt(0)>=48 && nums.codePointAt(0)<=57)){
                return Integer.parseInt(nums);
            }
            return 0;
        }
        char start = nums.charAt(0);
        Integer startNum = nums.codePointAt(0);
        if(start=='+' || start == '-' || (startNum >= 48 && startNum <= 57)){
            int before = 1;
            int index = 0;
            if(start == '-' || start == '+'){
                if (nums.length()<2){
                    return 0;
                }
                if(start == '-'){
                    before = -1;
                }
                index = 1;
            }
            return before*processNums(nums,index);
        }
        return 0;
    }
    private static int processNums(String nums,int start){
        double result = 0;
        for (int i = start; i < nums.length(); i++) {
            if(!(nums.codePointAt(i)>=48 && nums.codePointAt(i)<=57)){
                return 0;
            }
            int now = Integer.parseInt(nums.substring(i,i+1));
            result = 10 * result +now;
        }
        return (int)result;
    }

考虑多种异常情况,最总转化成一个处理正数的方法中

你可能感兴趣的:(2021-07-12 将string转int)