简体   繁体   中英

Array Index Out of Bounds Error in Java

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");
    }
}

this is a really simple program but for some reason, the array for the traincars goes out of bounds..

Why is this happening?

The problem is here:

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

When i equals traincars-1 you will be accessing elements i+1 , i+2 . and i+3 which are out of bounds of your trains array.

If your logic is calling for calculating totals of 4 consecutive elements of the array then your for loop should stop earlier:

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

In the last iteration of

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

You try to access trains[i+1] and this is bigger than the length of your trains array.

To make this for loop matter you should just do the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM