【问题标题】:How to compare array list value with previous value and avoid IndexOutOfBoundException如何将数组列表值与前一个值进行比较并避免 IndexOutOfBoundException
【发布时间】:2021-06-23 06:29:16
【问题描述】:

我有一些用 Java 编写的 Selenium 测试,我循环遍历 Array List 对象,我尝试根据这些规则为每个 UI 元素输入计算输入数据:

  • 对于列表索引 0,我必须检查所有元素,但只有在 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 ?
  • 如何从 1 开始循环 - 所以有前一个?如果您需要执行 0 案例,只需在循环之前执行 - 确保至少有 1..

标签: java for-loop arraylist indexoutofboundsexception


【解决方案1】:

来自 cmets 的回答: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) { 布尔结果 = 假;

if (i==0&&!currentValue.isEmpty()) {
    return true;
}

if (ignoreCase) {
    if (!currentValue.equalsIgnoreCase(previousValue)) {
        result = true;
    }
}
else {
    if (!currentValue.equals(previousValue)) {
        result = true;
    }
}
return result;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多