0

I'm trying to use this method to convert a number in any base to decimal.

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;
    }

But I end up getting array out of bound exception. What am I doing wrong here?

1 Answers1

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;
}
Niels Billen
  • 2,189
  • 11
  • 12