首页 > 解决方案 > 数组链接错误 java.lang.ArrayIndexOutOfBoundsException: 4

问题描述

我正在尝试制作一个程序,询问用户 4 个月的数据使用情况。然后确定他们是否超过了限制,如果超过了,额外的成本就会起作用。

但是当我尝试计算这个时我得到了一个错误。错误是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Simonly.main(Simonly.java:33)

这反过来

if (verbruik[i] > MB) {

我该如何解决这个问题?欢迎任何建议!

我的完整代码:

import java.util.Scanner;

public class Simonly {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Dit programma is gemaakt door Zakaria El-Bouchahati, IC201, 500785448\n");

        double PRIJS_PRIJS = 9.95;
        double MEEPRIJS = 0.025;
        int MB = 3000;
        double prijs = 0.0;
        double totaalPrijs = 0.0;
        String[] MAANDEN ={"juli", "augustus", "september", "oktober"};
        int[] verbruik = new int[MAANDEN.length];
        System.out.println("Geef je verbruik in MB per maand");

        int i;
        for(i = 0; i < MAANDEN.length; ++i) {
            do {
                System.out.print("\t" + MAANDEN[i] + ": ");
                verbruik[i] = input.nextInt();
                if (verbruik[i] < 0) {
                    System.out.println("Verkeerde input hoger dan nul!");
                }
            } while(verbruik[i] <= 0);
        }

        System.out.println("MAAND \t \t MB KOSTEN");

        for(i = 0; i <= verbruik.length; ++i) {
            if (verbruik[i] > MB) {
                prijs -= MB;
                totaalPrijs += prijs * MEEPRIJS;
            } else {
                totaalPrijs += MEEPRIJS;
            }
        }

        for(i = 0; i <= verbruik.length; ++i) {
            System.out.printf("-%20s " + MAANDEN[i]);
            System.out.println(MAANDEN[i] + "\t" + verbruik + "\t" + prijs);
        }

    }
}

标签: javaarrays

解决方案


MAANDEN.length is 4, verbruik length is 4, the loop will go from 0 to 4, that is: 0, 1, 2, 3, 4 which if you count them are 5 numbers. And the exception is telling you that 4 is an out of bounds value. To avoid this sort of problems and not to have to think about indexes, use the "enhanced form of for loop":

for (int verbruikValue : verbruik) {
    if (verbruikValue > MB) ...
}

推荐阅读