Java中的数组索引超出界限错误

时间:2013-12-05 01:37:58

标签: java arrays eclipse

package test1;

import java.util.Scanner;

public class Question2 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int traincars;
        int maxweight;
        int count = 0;
        int total = 0;

        maxweight = input.nextInt();
        traincars = input.nextInt();
        int[] trains = new int[traincars];

        for(int i = 0; i < traincars; i++)
        {
            trains[i] = input.nextInt();
        }

        if (total < maxweight)
        {
            for(int i = 0; i < traincars; i++)
            {
                total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
                count++;
            }
        }else
        {
            count = count + 3;
        }
System.out.println("count");
    }
}

这是一个非常简单的程序,但出于某种原因,火车车厢的数据超出界限..

为什么会这样?

2 个答案:

答案 0 :(得分:2)

问题在于:

        for(int i = 0; i < traincars; i++)
        {
            total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
            count++;
        }

i等于traincars-1时,您将访问元素i+1i+2。和i+3超出trains数组的范围。

如果你的逻辑要求计算数组的4个连续元素的总数,那么你的for循环应该提前停止:

for(int i = 0; i < traincars - 3; i++) {...}

答案 1 :(得分:1)

的最后一次迭代中
        for(int i = 0; i < traincars; i++)
        {
            total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
            count++;
        }

您尝试访问trains[i+1],这大于trains数组的长度。

要使这个for循环问题,您应该执行以下操作:

        for(int i = 0; i < traincars; i++)
        {
            total += trains[i]; //unless of course you need something else...
            count++;
        }