0

I am trying to access an array of characters by reading the array index from a String.

public class HelloWorld {

    public static void main(String[] args) {
        //             0123456789
        char[] code = {'A', 'B','C','D','E','F','G','H','I','J'};
        String orig = "0123456789";
        for ( int i=0; i <10; i++) {
            System.out.print(code[orig.charAt(i)]);
        }
    }

}

I was hoping for the output of ABCDEFGHIJ but instead I get a runtime error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 48
    at HelloWorld.main(HelloWorld.java:9)
1
  • Have you tried adding breakpoints within your loop to see what the code is actually doing? Commented Dec 23, 2014 at 2:55

4 Answers 4

3

This is because orig.charAt(i) returns a character which is ascii. So '0' is actually the number 48. You can easily fix this by doing:

code[orig.charAt(i) - 48];
Sign up to request clarification or add additional context in comments.

Comments

1

When you use orig.charAt(i) as the index, the char value gets converted to an int. Each character has a numerical value. '0', for instance, is 48. You can subtract the lowest character value you encounter to get an index in the correct range:

System.out.print(code[orig.charAt(i) - '0']);

Comments

1

Just index over the length of the string and get the character of the code array at that index... charAt will give you the literal int value which is obviously not what you want.

public static void main(String[] args) {
        //  0123456789
        char[] code = {'A', 'B','C','D','E','F','G','H','I','J'};
        String orig = "0123456789";
        for ( int i=0; i < orig.length(); i++) {
            System.out.print( code[i] );
        }
    }

Comments

1

Since array indexes are int it is automatically converted to an int.
But the int value of the char '0' is 48, hence the message "ArrayIndexOutOfBoundsException".
The below code should do it

System.out.print(code[orig.charAt(i)-48]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.