簡體   English   中英

Java中的數組索引超出界限錯誤

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

這是一個非常簡單的程序,但由於某種原因,火車車廂的數組超出界限。

為什么會這樣?

問題出在這里:

        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++) {...}

在最后一次迭代中

        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++;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM