
本文解释为何使用增强for循环配合`indexof()`会导致计数变量`numberpositive`无法正常递增,并提供基于索引的安全遍历方案,同时指出边界风险与修复建议。
在您的代码中,numberPositive 始终未按预期递增,根本原因在于以下这段逻辑:
for (String e : Variable) {
if (e.equalsIgnoreCase("VIB1 DISTANCE")) {
double priorDistance = Distance.get(Variable.indexOf(e) - 1);
double VibDistance = Distance.get(Variable.indexOf(e));
if ((VibDistance - priorDistance) >= priorDistance) {
numberPositive++;
}
}
}问题出在 Variable.indexOf(e) 的行为上:
- indexOf() 始终返回该字符串第一次出现的索引,而非当前遍历位置;
- 即使 e 在列表中多次出现(如多个 "VIB1 DISTANCE"),每次调用 indexOf(e) 都会返回首个匹配项的下标(例如总是 5),导致 priorDistance 和 VibDistance 总是取自同一对固定位置,严重偏离实际数据顺序;
- 更关键的是,equalsIgnoreCase() 在 indexOf() 中不生效——indexOf() 是纯字符精确匹配,大小写敏感,因此即使 e 是 "vib1 distance",indexOf("VIB1 DISTANCE") 也返回 -1,引发 IndexOutOfBoundsException 或逻辑跳过。
✅ 正确做法是改用传统索引 for 循环,确保 Variable 和 Distance 的访问严格对齐:
for (int i = 0; i < Variable.size(); i++) {
String currentVar = Variable.get(i);
if (currentVar != null && currentVar.equalsIgnoreCase("VIB1 DISTANCE")) {
// 安全检查:避免 i == 0 时访问负索引
if (i == 0) continue;
try {
double priorDistance = Distance.get(i - 1);
double vibDistance = Distance.get(i);
if (vibDistance - priorDistance >= priorDistance) {
numberPositive++;
}
} catch (IndexOutOfBoundsException ex) {
System.err.println("Warning: Distance list missing value at index " + i + " or " + (i-1));
}
}
}? 关键改进点说明:
立即学习“Java免费学习笔记(深入)”;
- 使用 i 直接索引两个 ArrayList,保证语义一致性;
- 显式判空 currentVar != null,防止 NullPointerException;
- 添加 i == 0 边界检查,规避 Distance.get(-1);
- 包裹 Distance.get() 调用在 try-catch 中,增强鲁棒性(因 CSV 解析可能产生长度不一致);
- 移除对 indexOf() 的依赖,彻底消除“重复值定位错误”和“大小写匹配失效”双重隐患。
⚠️ 额外建议:
- CSV 解析应使用专业库(如 OpenCSV 或 Apache Commons CSV),避免 split(",") 对含逗号字段(如 "Smith, John")的误切;
- numberExperiments 硬编码为 10.0 与实际数据行数(1215−5+1=1211)明显不符,建议动态统计有效实验次数,提升结果可信度;
- 变量命名请遵循 Java 规范:numberPositive(小驼峰)优于 numberPoistive(拼写错误且风格不一)。
通过以上重构,numberPositive 将严格依据数据实际顺序与条件逻辑准确递增,真正反映 "VIB1 DISTANCE" 行中满足差值阈值的有效数量。










