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

时间:2019-02-09 20:11:58

标签: java arrays

我要例外了,我不明白为什么

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)

3 个答案:

答案 0 :(得分:0)

因为数组索引从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);
}

答案 1 :(得分:0)

索引从0开始。您的长度为3,计数器变量(i)从1开始。

您可以使用

for (int i = 0; i < 3; i++)

答案 2 :(得分:0)

尝试一下,将其插入到主方法中

Scanner input = new Scanner(System.in);

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


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

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

        total = total + numbers[i];

    }


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