【问题标题】:ArrayIndexOutOfBoundsException Error Showing [duplicate]ArrayIndexOutOfBoundsException 错误显示 [重复]
【发布时间】:2015-11-12 18:21:23
【问题描述】:
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 个可用插槽。

【问题讨论】:

    标签: java arrays compiler-errors


    【解决方案1】:

    您的 marks 数组在 computemarks 方法中的大小为 6,但您在此处使用 x 索引设置它:

    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;
    

    【讨论】:

    • 哦,我现在明白了。有没有办法在不将标记设置为 18 个插槽的情况下解决此问题?
    • 是的,只是做一个额外的索引,它将被乘出循环
    • 不太清楚你的意思。请给我一个例子好吗?
    • @MartinRand 更新了答案,使用每次迭代都会增加 1 的索引
    • @MartinRand 你只做了 5 次迭代,因为 x
    猜你喜欢
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2015-11-08
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2011-12-01
    相关资源
    最近更新 更多