Java: ArrayIndexOutOfBoundsExeption

Java: ArrayIndexOutOfBoundsExeption

我创建了一个程序,可以将 10 长整数数组转换为 "Phone number" 格式。例如像这样: Solution.createPhoneNumber(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}) // => returns “(123) 456-7890”

这是我的代码: 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));



    }

}

我收到 ArrayIndexOutOfBoundsExeption,但我不知道为什么。在我的测试数组中,我有 10 个数字,如示例中所示。

if (i != 0 || i != 4) 总是正确的。如果 i 为 0,则 i != 0 为假项,但是,i != 4 为真,而 false || true 为真。因此,总是正确的,因此,计数器总是上升,因此,它达到 10 并且您 运行 超出输入数字。

尝试使用 && :)

像这样修改循环:

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

在您的代码中,您在 if 条件之外增加了 counter,因此 counter 可能会增加到 temp.length,这比 numbers.length 还多,所以 numbers[counter] 给你例外。

正如@rzwitserloot 所说,您应该将 || 替换为 &&