批量修改
您已经找到了需要修改的箱子,太好了!不过,用 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);
}
}
}