Java增强的循环和IndexOutOfBoundsException?
为什么在使用Java enhanced for loop时会出现Java增强的循环和IndexOutOfBoundsException?,java,loops,selenium,indexoutofboundsexception,Java,Loops,Selenium,Indexoutofboundsexception,为什么在使用Java enhanced for loop时会出现IndexOutOfBoundsException for (WebElement input : driver.findElements(By.cssSelector("input[type='text']"))) { if (input.isDisplayed()) { input.clear(); } } 它使用SeleniumWebDriver查找所有标记,并在显示时清除它们的内容(否则会引
IndexOutOfBoundsException
for (WebElement input : driver.findElements(By.cssSelector("input[type='text']"))) {
if (input.isDisplayed()) {
input.clear();
}
}
它使用SeleniumWebDriver查找所有
标记,并在显示时清除它们的内容(否则会引发不同的异常)。在一些测试中,我得到
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
堆栈跟踪的其余部分已打开
编辑
即使我添加了数组空性检查,仍然会发生此错误
List<WebElement> inputs = driver.findElements(By.cssSelector("input[type='text']"));
if (!inputs.isEmpty()) {
for(WebElement input : inputs) {
}
}
List inputs=driver.findElements(By.cssSelector(“input[type='text']);
如果(!inputs.isEmpty()){
for(WebElement输入:输入){
}
}
您能否检查此语句的结果driver.findElements(通过.cssSelector(“输入[type='text'])
似乎在增强循环开始执行之前,driver.findElement
s就出现了IndexAutofBound异常。您可以尝试在控制台上调试或打印该值
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
这指定您已在索引1处输入循环,尽管数组的大小为0。您应该在索引0处输入。这很奇怪。因此,这表明错误是由下面的代码抛出的
尝试并运行一些调试-在此之前,尝试并打印
driver.findElements(By.cssSelector("input[type='text']"))
试着看看有没有什么东西被退回
我可能会发表评论,但没有足够的代表
它也是一个for-each循环。由
driver.findElements()
返回的迭代器
有严重问题。我已经解决了这个问题,但仍然-我应该如何正确处理这种情况?您可能正在运行旧版本的Selenium吗?