我有java.lang.ArrayIndexOutOfBoundsException

时间:2015-10-24 07:25:05

标签: java for-loop

在预测游戏中,两个或更多玩家试图预测一系列即将到来的体育比赛的得分。然后根据下面列出的类别的总和来评估每个玩家的预测。这些描述使用以下变量:

S1:团队1获得的实际分数。

S2:团队2获得的实际分数。

P1:球员对球队1的预测得分。

P2:球员对球队2的预测得分。

但我有异常java.lang.ArrayIndexOutOfBoundsException

public void game() {
    int s1, s2, p1, p2, winner, team1, team2, pointSpread, total = 0;

    int testCase = scan.nextInt();

    for (int k = 0; k < testCase; k++) {

        int p = scan.nextInt();
        int c = scan.nextInt();

        int[]result = new int[p];
        String[]pName = new String[p];

        for (int i = 0; i < p; i++) {
            pName[i] = scan.next();

            for (int j = 0; j < c; j++) {
                p1 = scan.nextInt();
                p2 = scan.nextInt();
                s1 = 20;
                s2 = 13;

                if (s1 > s2 && p1 > p2) {
                    winner = 10;
                }
                if (s1 < s2 && p1 < p2) {
                    winner = 10;
                } else {
                    winner = 0;
                }

                team1 = 5 - Math.abs(s1 - p1);
                team2 = 5 - Math.abs(s2 - p2);
                pointSpread = 5 - Math.abs(p1 - p2)-(s1 - s2);

                total += winner + team1 + team2 + pointSpread;
                result[i] = total;
            }
        }

        //compare players scores
        int max = result[0], playerNo = 0;
        for (int m = 1; m <= p; m++)//this line error
            if (max < result[m]) {
                max = result[m];
                playerNo = m;
            }

        System.out.println(pName[playerNo]);
    }
}

1 个答案:

答案 0 :(得分:2)

将错误行更改为for(int m=1; m<p;m++)