1
for (int i = 0; i < 15; i+=3) {
        System.out.print("Enter Exam Mark:");
        Marks[i] = input.nextInt();
        System.out.print("Enter Coursework Mark:");
        Marks[i+1] = input.nextInt();
        System.out.print("Enter Weighting:");
        Marks[i+2] = input.nextInt();

    }


public double[] computemarks(int[] Marks) {

    double[] marks = new double[6];
    double computedmark;

    for (int x = 0; x < 15; x+=3) {

        if (Marks[x] >= 35 && Marks[x+1] >= 35) {

            computedmark = ((Marks[x+1] * Marks[x+2]) + (Marks[x] * (100.0 - Marks[x+2]))) / 100.0;

        } else {

            computedmark = Math.min(Marks[x], Marks[x+1]);

        }

        marks[x] = computedmark;

    }
    return marks;

}

Why is "ArrayIndexOutOfBoundsException" showing during runtime? I've played around with the for loops but it's still not working.

FYI, The Marks array has 18 available slots in memory.

M-R
  • 411
  • 2
  • 6
  • 15

1 Answers1

1

Your marks array has a size 6 in the computemarks method, but you are setting it's with x index, here:

marks[x] = computedmark;

which is taken out of the loop and after the 3rd iteration is equals to 9 yet.

update according to your comment, it could be made like:

int idx = 0; //here is additional index declared
for(int x=0; x < 15; x+=3) {

    if (Marks[x] >= 35 && Marks[x+1] >= 35) {

        computedmark = ((Marks[x+1] * Marks[x+2]) + (Marks[x] * (100.0 - Marks[x+2]))) / 100.0;

    } else {

        computedmark = Math.min(Marks[x], Marks[x+1]);

    }

    marks[idx++] = computedmark; //here is additional index is used with post incrementing

}
return marks;
Stanislav
  • 27,441
  • 9
  • 87
  • 82
  • Oh, I see now. Is there a way to fix this without setting marks to 18 slots? – M-R Nov 12 '15 at 18:30
  • 1
    Yes, just make an additional index, which will be multiplied out of the loop – Stanislav Nov 12 '15 at 18:30
  • Not quite sure what you mean. Could you provide me with an example please? – M-R Nov 12 '15 at 18:32
  • @MartinRand updated an answer, use an index which will be increased by 1 on every iteration – Stanislav Nov 12 '15 at 18:37
  • Thanks for that! The error is no longer appearing, however, the 6th value of marks is showing as 0... – M-R Nov 12 '15 at 18:43
  • 1
    @MartinRand you make just 5 iterations, because of the x<15, but it has to be x<=15 or just x<16. take a look, during the 6th iteration, x is equals to 15 and ignored – Stanislav Nov 12 '15 at 18:47