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;
}
为什么在运行时显示“ArrayIndexOutOfBoundsException”? 我玩过for循环,但它仍然没有用。
仅供参考,Marks阵列在内存中有18个可用插槽。
答案 0 :(得分:1)
您的marks
数组在computemarks
方法中的大小为6,但是您使用x index设置它,在此处:
marks[x] = computedmark;
取出循环,第3次迭代后等于9。
更新根据您的评论,可以像:
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;