Search code examples
javaarraysindexingcharindexoutofboundsexception

Array index out of bounds error even though the indices are within the array length


I was trying to write a java program where every digit of an input integer is printed in words.

For example: input 123 should produce an output "one two three".

I wrote the following program that takes an integer value, then converts it into a string. I then iterated over the characters of the string and converted them to integer values, which I later used as indices for the array.

But I'm getting ArrayIndexOutOfBoundsException.

Index 49 out of bounds for length 10

My code:

public class DigitsAsWords {
    static void Print_Digits(int N){
        String arr[] = {"zero","one", "two", "three", "four","five", "six", "seven", "eight", "nine"};
        String st = Integer.toString(N);
        System.out.println(st);
        char s;
        int a;
        for (int i=0; i<st.length(); i++){
            s = st.charAt(i);
            a = Integer.valueOf(s);
            System.out.print(arr[a]+" ");
        }
    }
    public static void main (String args[]){
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        Print_Digits(a);
    }
}

Solution

  • This is the place your code is failing at:

    a = Integer.valueOf(s);
    

    Instead of converting '1' to 1 as you were expecting, it converts '1' into the ascii equivalent, 49.

    To avoid this:

    a = Character.getNumericValue(s);
    

    This will convert '1' to 1, and so on.