I am currently having trouble finding what I am doing wrong with this program. I am specifically asked to follow the directions given such as using double I, weightLimit, []W;
I continuously receive ArrayIndexOutOfBoundsException:6 as well as issues on lines 53 and 39
What is it that I am not doing correctly?
import java.util.Scanner;
public class RecursiveKnapsack {
static double max(double a, double b) {
if (a > b)
return a;
else return b;
}
public static double m (int i, double weightLimit, double [] w) {
if(i <= 0 || weightLimit == 0)
return 0;
else if (w[i] > weightLimit)
return m(i-1,weightLimit,w);
else return max(m(i-1, weightLimit, w),w[i] + m(i-1, weightLimit-w[i], w));
}
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
//NumberofItems
System.out.println("Enter the number of items: ");
int i = input.nextInt();
//Weight of Items
System.out.println("Enter the weights for each item: ");
double[] w = new double[i];
//Inserting input in array
for (int x=0; x < i; x++){
w[x] = input.nextDouble();
}
//Limit
System.out.println("Enter the weight limit for the bag: ");
double weightLimit = input.nextDouble();
System.out.println("The maximum weight of the items placed in the bag is " + m(i,weightLimit,w));
}
}