-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];
        }
    }
    tp = tp + (x[i] * profit[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);
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 line 21 awhere it says tp = tp + (x[i] * profit[i]); how could i solve this

Shahd
  • 1
  • 1
  • 1
    Look at the `for` loop bounds (i.e., consider the range of `i`). Then think about what the maximum index is for an array of length `n`. – Slaw Apr 12 '23 at 17:50

1 Answers1

0

You are initiating an array of size n, meaning the indices go from 0 to n-1. Your for loop starts from 0 and is <= n meaning it includes n. The last element will try to go at index n, but that it not possible as the last index is n-1. Possible fix for that line is using < n instead of <= n

  • it gave me the same exception just in different line which is line 21 tp = tp + (x[i] * profit[i]); – Shahd Apr 12 '23 at 17:54
  • You need to develop more intuition and ask the right questions. The problem is that this function does not define the profit array, and you are using a `for` loop with size `n` on both the `x` array which is of size `n`, but the `profit` array is not defined in that function. Meaning you defined elsewhere, meaning its probably a different size than x, and probably smaller than x. If you are looking for something that can vary in size, look into ArrayLists – Remus Mocanu Apr 12 '23 at 17:58
  • 1
    @Shahd Don't just apply the fix suggested in this answer. You must _understand_ the solution. Then you can generalize the fix to any index-out-of-bounds error you get. – Slaw Apr 12 '23 at 18:01