0

我正在尝试使用此方法将任何基数的数字转换为十进制。

public static int convertToDecimal(String str, int base){

        int v = 0;
        int total = 0;
        int pow = 0;
        str = str.toUpperCase();
        for(int i = str.length(); i > -1; i--){
            char c = str.charAt(i);
            if (c >= '0' && c <= '9') {
                v = c - '0';
            }else if (c >= 'A' && c <= 'Z'){
                v = 10 + (c - 'A');
            }
            total += v * Math.pow(base,pow);
            pow++;
        }
        return total;
    }

但我最终得到了数组越界异常。我在这里做错了什么?

4

1 回答 1

3

As @HovercraftFullOfEels already noted. Strings are zero based. You are starting at i=str.length() which throws the ArrayIndexOutOfBoundsException since the largest possible index is i=str.length()-1.

public static int convertToDecimal(String str, int base) {
    int v = 0;
    int total = 0;
    int pow = 0;
    str = str.toUpperCase();
    for (int i = str.length() - 1; i >= 0; i--) {
        char c = str.charAt(i);
        if (c >= '0' && c <= '9')
            v = c - '0';
        else if (c >= 'A' && c <= 'Z')
            v = 10 + (c - 'A');
        total += v * Math.pow(base, pow);
        pow++;
    }
    return total;
}
于 2015-01-17T14:08:31.300 回答