public class AccumulatedData { public static void main(String args[]) { ArrayList<Double> weights = new ArrayList<Double>(); weights.add(145.0); weights.add(146.5); weights.add(146.5); weights.add(147.0); weights.add(146.0); weights.add(148.0); weights.add(148.5); ArrayList<Double> printWeightChanges = getWeightChanges(weights); System.out.println(weights); } public static ArrayList<Double> getWeightChanges(ArrayList<Double> weights) { for (int i = 0; i < weights.size() - 1; i++) { weights.set(i, (weights.get(i + 1) - weights.get(i))); } return weights; }}我在上面尝试遍历数组列表的所有元素并打印出它们各自的连续差异(取数组列表的索引之一并减去索引零)但是,我的 for 循环似乎遍历了所有元素,打印了它们各自的差异,然后添加我的初始数组的最后一个数字到我的新数组列表的末尾,其中包含所有差异。我该如何解决?公共课PartA {public static void main(String args[]) { ArrayList<Double> weights = new ArrayList<Double>(); weights.add(145.0); weights.add(146.5); weights.add(146.5); weights.add(147.0); weights.add(146.0); weights.add(148.0); weights.add(148.5); ArrayList<Double> printWeightChanges = getWeightChanges(weights);新尝试:}/** * Part a */public static ArrayList<Double> getWeightChanges(ArrayList<Double> weights) { ArrayList<Double> weightDifferences = new ArrayList <Double>(); for (int i = 0; i < weights.size() - 1; i++) { weightDifferences.add(i, weights.get(i + 1) - weights.get(i)); } System.out.println(weightDifferences); return weightDifferences; }}
2 回答
炎炎设计
TA贡献1808条经验 获得超4个赞
这是因为您如何定义循环限制:
for (int i = 0; i < weights.size() - 1; i++)
与数组 ( ) 相比,循环更改的元素少一个i < weights.size() - 1。
我建议为差异创建另一个列表,如下所示:
public static List<Double> getWeightChanges(ArrayList<Double> weights) {
List<Double> diffs = new ArrayList<>();
for (int i = 0; i < weights.size() - 1; i++) {
diffs.add(weights.get(i + 1) - weights.get(i));
}
return diffs;
}
慕神8447489
TA贡献1780条经验 获得超1个赞
您尝试输出的长度将与原始列表不同(特别是少一个数据点)。您要么需要remove()
列表的最后一个元素,要么创建一个新列表以不同大小输出。
由于您的原始列表包含 7 个双精度数,并且您更改了前 6 个,因此列表的最后一个元素保持不变
添加回答
举报
0/150
提交
取消