Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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: 123 is "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 it is showing array index out of bounds error.

Index 49 out of bounds for length 10

    import java.util.*;

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading