java - 如何将数组列表值与前一个值进行比较并避免 IndexOutOfBoundException
问题描述
我有一些用 Java 编写的 Selenium 测试,我循环遍历 Array List 对象,我尝试根据这些规则为每个 UI 元素输入计算输入数据:
- 对于列表索引 0,我必须检查所有元素,但如果 UI 元素不为空,则仅将其值输入到 UI 元素中。
- 对于所有其他索引,我需要检查每个元素,但如果值已从先前的值更改,即使它是空的(而先前的不是),只有将它们的值输入到 UI 元素。
所以我有一个循环:
for (int i = 0; i < testDataML.size(); i++) {
...
inputMLData(i);
CommonMethods.clickCalculate(path, outputPath, i);
...
}
然后在函数 inputMLData 中,我们为每个 UI 元素重复这些块:
if (i == 0) {
if (!testDataML.get(i).In_VersionID.isEmpty())
setInputElementPathML(false, "VersionID", testDataML.get(i).In_VersionID);
} else if (!testDataML.get(i).In_VersionID.equals(testDataML.get(i - 1).In_VersionID))
setInputElementPathML(false, "VersionID", testDataML.get(i).In_VersionID);
而这个逻辑目前是基于我之前写的这两点工作的。但基本上我必须有两个条件 - if (i==0)然后使用else if以避免在第一次循环迭代时获得 IndexOutOfBoundException 。在这两个条件之后,我调用了相同的函数。所以问题是我怎样才能避免这种异常?我不想使用 try 块,因为它会导致基本相同数量的代码。整个 if 逻辑我可以转移到另一个函数,但我仍然必须为该函数提供参数 testDataML.get(i - 1).In_VersionID
解决方案
评论回复:testDataML.get( (i ==0)? i : i-1).In_VersionID
。inputMLData 中的最终结果如下所示:
if (CommonMethods.isNewInput(testDataML.get(i).In_VersionID, testDataML.get((i ==0)? i : i-1).In_VersionID, i, false)) {
setInputElementPathML(false, "VersionID", testDataML.get(i).In_VersionID);
}
isNewInput 现在看起来像这样:
public static boolean isNewInput (String currentValue, String previousValue, int i, boolean ignoreCase) { boolean result = false;
if (i==0&&!currentValue.isEmpty()) {
return true;
}
if (ignoreCase) {
if (!currentValue.equalsIgnoreCase(previousValue)) {
result = true;
}
}
else {
if (!currentValue.equals(previousValue)) {
result = true;
}
}
return result;
}
推荐阅读
- node.js - 节点,React,同时出现 EADDRINUSE :::8000 错误
- html - HTML
- assembly - 无需汇编程序即可在可执行文件中运行的程序集类型名称
- java - 如何构建 java.io.File 代码以支持 JUnit 测试?
- git - 合并具有不相关历史的两个存储库的更改
- c - 在c中生成随机码
- python - 如何使用 selenium 从源代码中未出现的元素中获取 HTML 代码?
- .htaccess - .htaccess 重定向 301 必须存在尾部斜杠 - 为什么?
- apache-spark - 结构流式传输:前 n 行
- javascript - 如何在单击时更改背景颜色和字体颜色(无 jQuery)?