编译后数组超出范围错误

时间:2014-04-15 04:29:53

标签: java arrays

我无法弄清楚为什么在运行程序后我不断让数组超出界限错误。

import java.util.Scanner;
public class Judge {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter a degree of difficulty between 1.2 - 3.8");
    String difficultyString = keyboard.nextLine();
    double difficulty = Double.parseDouble(difficultyString);
    int[] scores = new int[6];
    for(int i = 0; i<scores.length; i++){
        System.out.println("Enter the score of a judge");
        String tempWord = keyboard.nextLine();
        int temp = Integer.parseInt(tempWord);
        scores[i] = temp;
    }
    int low = Math.min(Math.min(Math.min(Math.min(scores[0], scores[1]), Math.min(scores[2], scores[3])),Math.min(scores[4], scores[5])), scores[6]);

    int high = Math.max(Math.max(Math.max(Math.max(scores[0], scores[1]), Math.max(scores[2], scores[3])),Math.max(scores[4], scores[5])), scores[6]);
    int additon = scores[0] + scores[1] + scores[2] + scores[3] + scores[4] + scores[5] + scores[6];
    int score = (additon - low) - high;
    double actualScore = (score * difficulty) * 0.6;
    System.out.println("The score of the diver is : " + actualScore);
}

}

忽略我的代码。我知道这很邋and而且不是最简单的方法,但我到底做错了什么?

3 个答案:

答案 0 :(得分:6)

您的scores数组的长度为6,表示0到5的索引,6个元素。您正在访问它的第6个索引。您最多只能添加第5个索引,如下所示

int additon = scores[0] + scores[1] + scores[2] + scores[3] + scores[4] + scores[5];

答案 1 :(得分:3)

从0到5的数组,但是你试图让scores[6]不可能只有数组indexOutOfBoundException

答案 2 :(得分:3)

int[] scores = new int[6];表示您在数组中创建 6 元素。

您创建的 6 元素是:

scores[0] //1st element
scores[1] //2nd element
scores[2] //3rd element
scores[3] //4th element
scores[4] //5th element
scores[5] //6th element

您的代码提到scores[6]这是一个不存在的元素(超出数组范围)。