Get startedGet started for free

Batch Changing

You have found the correct box to change. Hurray ! Unfortunately, with a forEach loop, you cannot easily change the content. To that end, you slightly change your program and use a for loop. The weight of the new bag is 198.

This exercise is part of the course

Intermediate Java

View Course

Exercise instructions

  • Write down the correct limit for the iterator.
  • Input the correct index to change the list weights. It should work even if the element's position changes.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

class WeightChanger {
  public static void main(String[] args) {
    int[] weights = {198, 190, 188, 187, 190, 198, 201, 250, 203, 210, 205, 170, 180, 200, 203, 210, 180};

    // Write down the correct limit for the iterator
    for (int i = 0; i < ____.____; i++) {
      int weight = weights[i];
      if (weight > 220) {
        // Input the correct index to change the list. It should work even if the element changed location.
        weights[____] = 198;
      }
    }

    for (int weight : weights){
      System.out.println(weight);
    }
  }
}
Edit and Run Code