数组for循环错误

时间:2014-11-09 22:05:55

标签: java arrays for-loop

我一直收到错误,我不知道如何修复它 我得到的错误是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Ch7Ex1NumberAboveAverage_TimmyHernandez.main(Ch7Ex1NumberAboveAverage_TimmyHernandez.java:35)

我的代码:

public class Ch7Ex1NumberAboveAverage_TimmyHernandez {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("How many temperatures do you have?");
        int entry = keyboard.nextInt();
        double[] temperature = new double[entry];

        System.out.println("Please enter the " + entry + " temperatures.");

        int index = 0;
        double total = 0;
        for (index = 0; index < temperature.length; index++);
        {
            temperature[index] = keyboard.nextDouble();
            total = total + temperature[index];
        }

        double average = (total / temperature.length);
        System.out.println("The average temperature is" + average + ".");

        System.out.println("The following temperatures are higher than the average temperature:");
        for (index = 0; index < temperature.length; index++);
        {
            if (temperature[index] > average);
            {
                System.out.println("Temperature " + (index + 1) + ":" + temperature[index]);
            }
        }
    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

在你的代码中你有一个循环  for (index = 0; index < temperature.length; index++);

最后有一个分号。因此,当循环结束index值为temperature.length然后在下一行时,您将尝试访问超出数组大小的元素。这是人们常见的错误/拼写错误,很难在快​​速代码演练中找到。

将其更改为

for (index = 0; index < temperature.length; index++)

ArrayIndexOutOfBoundsException始终为您提供程序尝试访问阵列的索引值。通过查看索引的行号和可能值,可以快速纠正这种异常。