我怎么会得到IndexOutOfBoundsException
while 使用 Java 增强的 for 循环?我的代码如下所示
for (WebElement input : driver.findElements(By.cssSelector("input[type='text']"))) {
if (input.isDisplayed()) {
input.clear();
}
}
它使用 Selenium WebDriver 来查找所有 <input type="text" />
标签并清除它们的内容(如果它们显示)(否则会抛出不同的异常)。在一些测试中我得到了
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
堆栈跟踪的其余部分位于 Pastebin .
编辑
即使我添加了数组空性检查,此错误仍然发生
List<WebElement> inputs = driver.findElements(By.cssSelector("input[type='text']"));
if (!inputs.isEmpty()) {
for(WebElement input : inputs) {
}
}
最佳答案
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
这表明您已在索引 1 处进入循环,尽管数组的大小为 0。您应该在索引 0 处进入。这很奇怪。因此,这表明错误是由参见下文
引发的 <小时/>尝试运行一些调试 - 在此之前,尝试并打印
返回的对象 driver.findElements(By.cssSelector("input[type='text']"))
并尝试看看是否确实返回了任何内容。
我会发表评论,但没有足够的代表。
这也是一个 for-each 循环。
关于Java增强for循环和IndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17162461/