有人可以解释为什么对我的数组进行这些特定更改可以修复我的错误吗?

Can someone explain why these specific changes to my array fix my errors?

我开始通过在线教程自学 Java,但我很难理解在这种情况下我应该做什么:

任务:"Change the values in numbers so it will not raise an error."

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        int length = numbers[3];
        char[] chars = new char[length];
        chars[numbers.length + 4] = 'y';
        System.out.println("Done!");
    }
}

我检查了解决方案,但仍然不明白错误是什么以及如何修复它:

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        int length = numbers[2];
        char[] chars = new char[length];
        chars[numbers.length - 1] = 'y';
        System.out.println("Done!");
    }
}

编辑: 我现在明白了 3 到 2 的变化,但为什么要把 +4 变成 -1?

我认为正确的答案是更改 "the values in 'numbers'"

    int[] numbers = {1, 2, 3, 9};

或者更确切地说,添加任何大于或等于 9 的数字都可以,实际上。

这意味着 'length' 将为 9,'chars' 数组的长度为 9,并且元素 [4(*) + 4] 的索引不会产生 ArrayOutOfBoundsException

(*) 4 是 'numbers' 数组的长度。

像这样:

public class Main {
  public static void main(String[] args) {
    int[] numbers = {1, 2, 3, 9};
    int length = numbers[3];
    char[] chars = new char[length];
    chars[numbers.length + 4] = 'y';
    System.out.println("Done!");
  }
}

让我们逐行分析。

int[] numbers = {1, 2, 3};

这将创建一个包含 3 个元素的数组。第一个是1,第二个是2,第三个是3.

int length = numbers[3];

上述数组的长度是3,我们已经知道了。由于第三个元素的值也是 3,因此您使用该值。但是数组的索引是从0开始的,所以numbers[3](3是索引)会报错。 numbers[0]是1,numbers[1]是3,numbers[2]是3。numbers[3]是错误的。

char[] chars = new char[length];

这将创建一个新数组,这次不是数字数组,而是字符数组。例如 'a''b''y'。数组长度为3.

chars[numbers.length + 4] = 'y';

numbers.length 是 3。加上 4 是 7。如您所知,索引 7 指的是数组的第八个元素。由于 chars 只有 3 个元素长,这会导致错误。所以我们必须把 4 变成一些东西,当加上 3 时,小于 3 但大于或等于 0。所以你可以把它改成 -1、-2 或 -3。

System.out.println("Done!");

这只会向控制台输出 "Done!",这里没有魔法。

这已经得到回答,我自己的回答可能不是最好的,但我只是注释掉了 chars[[=​​14=] + 4] = 'y';。 我让它看起来像这样 **//**chars[[=​​14=] + 4] = 'y';