
java 的增强型 for 循环无法提供索引访问,导致 `variable.indexof(e)` 总是返回首次匹配位置(且区分大小写),造成逻辑错位和计数失效;应改用传统索引循环确保一一对应。
在您提供的代码中,numberPositive 变量未按预期递增,根本原因在于对 ArrayList
indexOf() 返回首个匹配项索引,而非当前迭代位置
即使 "VIB1 DISTANCE" 在列表中重复出现,Variable.indexOf(e) 每次都返回它第一次出现的位置(例如始终是 5),导致 Distance.get(Variable.indexOf(e)-1) 和 Distance.get(Variable.indexOf(e)) 总是读取同一组距离值,无法实现“逐行比对相邻距离”的业务逻辑。indexOf() 区分大小写,而 equalsIgnoreCase() 不生效
e.equalsIgnoreCase("VIB1 DISTANCE") 判断成功,但 Variable.indexOf(e) 内部仍执行严格字符串匹配(equals()),若原始 CSV 中数据为 "vib1 distance" 或 "Vib1 Distance",indexOf() 将返回 -1,触发 IndexOutOfBoundsException(虽被静默忽略,但逻辑已中断)。
✅ 正确解法:使用基于索引的传统 for 循环,直接通过 i 同步访问 Variable 和 Distance:
for (int i = 0; i < Variable.size(); i++) {
String currentVar = Variable.get(i);
if (currentVar != null && currentVar.equalsIgnoreCase("VIB1 DISTANCE")) {
// 注意:i == 0 时无 priorDistance,需跳过
if (i == 0) continue;
try {
double priorDistance = Distance.get(i - 1);
double vibDistance = Distance.get(i);
// 条件:(当前距离 - 前一距离) ≥ 前一距离 → 即当前距离 ≥ 2 × 前一距离
if (vibDistance - priorDistance >= priorDistance) {
numberPositive++;
}
} catch (IndexOutOfBoundsException ex) {
System.err.println("Warning: Distance list index out of bounds at position " + i);
}
}
}? 关键注意事项:
- 边界防护必加:当 i == 0 时,i-1 为负数,直接调用 Distance.get(-1) 会抛出异常,必须跳过;
- 空值检查:CSV 解析可能产生 null 字段(尤其空单元格),Variable.get(i) 前建议判空;
- 异常处理细化:将 NumberFormatException 和 IndexOutOfBoundsException 分开捕获,避免掩盖真实问题;
- 变量命名规范:numberPositive 应改为 numberPositive(驼峰式),类名 project 应首字母大写(Project)以符合 Java 命名约定。
最后,请确认 CSV 数据结构是否严格满足:每行 variableColumn 列为 "VIB1 DISTANCE" 时,其前一行对应列(targetColumn)的数值可被安全解析为 double。逻辑修正后,numberPositive 将准确统计所有满足增长条件的 "VIB1 DISTANCE" 出现次数。










