You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Java的ArrayIndexOutOfBoundsException?背包代码报错分析

解决java.lang.ArrayIndexOutOfBoundsException异常及0-1背包代码问题

报错直接原因

你遇到的Index 5 out of bounds for length 5错误,是因为第二个for循环结束后,变量i的值等于n(这里n=5),而数组x和profit的长度都是5,合法索引范围是0到4。此时执行tp = tp + (x[i] * profit[i]);,会访问超出数组边界的索引5,触发异常。

ArrayIndexOutOfBoundsException异常通用成因

  • 数组索引取值小于0,或者大于等于数组实际长度
  • 循环结束后未重置索引变量,直接复用导致索引越界
  • 错误计算数组长度,比如误将其他变量当作数组长度使用

异常预防方法

  • 访问数组前确认索引在0 <= 索引 < 数组.length区间内
  • 循环结束后若需再次使用索引变量,务必重新赋值或重置
  • 优先使用增强for循环(for-each)遍历数组,避免手动维护索引出错
  • 可添加索引合法性检查,比如用if (i >=0 && i < arr.length)判断后再访问

0-1背包代码的报错解决

你的代码中,tp = tp + (x[i] * profit[i]);这一行完全多余——第二个for循环已经遍历了所有物品(i从0到n-1),并在选中物品时累加了利润。直接删除这行代码即可解决报错。

修正后的完整代码:

static void knapsack(int n, int[] weight, int[] profit, int capacity){
    int x[] = new int[n] ;
    int tp=0; //total profit
    int i;

    for( i = 0; i < n; i++){
        x[i] = 0;
    }
    
    for( i = 0; i < n; i++){
        
        if(weight[i] > capacity){
            x[i] = 0;
        }
        else{
            x[i] = 1;
            tp = tp + profit[i];
            capacity = capacity - weight[i];
        }
    }
    System.out.print("The vectors:");
    for(i = 0; i < n; i++){
        System.out.print("[" + x[i] + "]");
    }
    System.out.println("The maximum profit is:" + tp);
    
}
// Driver code
public static void main(String args[])
{
    int profit[] = new int[] { 4, 2, 1, 10, 2 };
    int weight[] = new int[] { 11, 2, 1, 4, 1 };
    int W = 15;
    int n = profit.length;
    knapsack(n , weight, profit, W);
}

注意:这段代码是贪心算法实现,仅能得到近似解,若需要0-1背包的最优解,建议使用动态规划方法。

内容的提问来源于stack exchange,提问作者Shahd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:22:53