Search code examples
javaindexoutofboundsexception

Java: ArrayIndexOutOfBoundsExeption


I created a program that should convert a 10 long int array to a "Phone number" format. For example like this: Solution.createPhoneNumber(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}) // => returns "(123) 456-7890"

Here is my code: Solution.java:

public class Solution {

    public static String createPhoneNumber(int[] numbers) {

        int counter = 0;

        char[] temp = new char[numbers.length + 4];

        temp[0] = '(';
        temp[4] = ')';
        temp[5] = ' ';
        temp[9] = '-';

        for (int i = 0 ; i < temp.length ; i++)
        {
            if (i!=0 && i!=4 && i!=5 && i!=9)
            {
                temp[i] = (char) numbers[counter];
                counter++;
            }

        }

        String solution = new String(temp);

        return solution;

    }
}

Test.java:

public class Test {

    public static void main(String[] args) {

        int[] test = new int[10];

        test[0] = 1;
        test[1] = 2;
        test[2] = 3;
        test[3] = 4;
        test[4] = 5;
        test[5] = 6;
        test[6] = 7;
        test[7] = 8;
        test[8] = 9;
        test[9] = 0;

        System.out.println(Solution.createPhoneNumber(test));



    }

}

I get ArrayIndexOutOfBoundsExeption and I don't know why. In my test array I have 10 numbers, like in the example.


Solution

  • Modify your loop like this:

    for (int i = 0 ; i < temp.length ; i++) {
        if (i!=0 && i!=4 && i!=5 && i!=9) {
            temp[i] = (char)(numbers[counter] + (int)'0');
            counter++;
        }
    }
    

    In your code, you increase the counter outside if condition, so counter may increase up to temp.length which is more than numbers.length, so numbers[counter] gives you exception.

    And as @rzwitserloot said, you should replace || with &&