開始使用免費開始

批次變更

你已經找到了要變更的正確箱子,太好了!不過,用 forEach 迴圈不太容易直接修改內容。為此,請稍微調整程式,改用 for 迴圈。新包裹的重量是 198

本練習屬於課程

Java 中級

檢視課程

練習說明

  • 寫出迭代器正確的上限
  • 輸入正確的索引來變更清單 weights。即使元素的位置改變,也應該能正常運作。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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);
    }
  }
}
編輯並執行程式碼