ArrayIndexOutOfBoundsException:索引 3 超出长度 3 的范围

新手上路,请多包涵

我遇到异常,我不明白为什么

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int n = 3;
    int[] numbers = new int[n];
    float total = 0;

    for (int i = 1; i <= 3; i++) {

        System.out.println("Please type the number " + i + ":");
        numbers[i] = input.nextInt();

        total = total + numbers[i];

    }

    System.out.println("The average of the 3 number is: " + total / n);
}

安慰:

 Please type the number 1:
3
Please type the number 2:
4
Please type the number 3:
5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    at Ejercicio12.main(Ejercicio12.java:17)

原文由 im_cool 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

因为数组索引从 0 开始

 public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int n = 3;
int[] numbers = new int[n];
float total = 0;

for (int i = 0; i <= 2; i++) {
int row=i+1;
    System.out.println("Please type the number " + row + ":");
    numbers[i] = input.nextInt();

    total = total + numbers[i];

}

System.out.println("The average of the 3 number is: " + total / n);
}

原文由 AMA 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您遇到下面列出的错误

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException:索引 3 超出长度 3 的范围

var arr = arrayOf("One","Two","Three")
 println(arr[3])

在这个数组中我们刚刚定义了三个值和索引从 0 开始,所以数组中不存在索引 3 这就是它给出这个异常的原因

尝试打印包含在 Array As As 中的索引值

println(arr[1])

原文由 Rehan Khan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题