This is the same example as earlier, but using a for-loop instead of a while-loop and checking that the index variable, k, is within bounds.
Where is the error? What addition to the loop condition would fix this error?
int[] wt = {1, 2, 3, 5, 9, 15, 15, 16, 20}; int targetWeight; Scanner in = new Scanner(System.in); targetWeight = in.nextInt(); int sum = 0; // Total Weight of packed items for(int k = 0; k < wt.length && sum < targetWeight; k++) { sum += wt[k]; } System.out.printf("target weight = %d, " + "packed weight = %d, " + "number items packed = %d\n", targetWeight, sum, k);