-1

I'm trying to make a program which asks user input about data usage for 4 months. Then to determine whether they exceeded the limit or not and if so extra costs come in play.

But I'm getting an error when I try to calculate this. The error is:

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

which revers to

if (verbruik[i] > MB) {

How can I solve this ? Any suggestions are welcome!

My complete code:

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

    }
}
GBlodgett
  • 12,612
  • 4
  • 26
  • 42
Hi tE
  • 144
  • 8

2 Answers2

0

Problem is you’re using lesser than or equal in your for loop. Length is 4, so variable i should not have a value over 3, as arrays start from position 0.

Take the equal sign out and it will stop getting out of bounds.

for(i = 0; i < verbruik.length; ++i) {...
Tomaz Fernandes
  • 964
  • 1
  • 7
  • 12
0

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) ...
}
Perdi Estaquel
  • 757
  • 1
  • 5
  • 21