如何在Java中中断if循环如何在、Java、if

2023-09-03 14:47:25 作者:ご流浪青年﹌

我尝试在单击某个元素后放置分隔符,但在单击该元素后,它尝试再次迭代

for (int i = 1; i < tableSize; i++) {       
        final List<WebElement> columnElements = tableRows.get(i).findElements(By.tagName("td"));
        for(WebElement columnElement : columnElements) {
            if(columnElement.getText().equalsIgnoreCase(alias)) {

                findElement(By.xpath(button.replace("{rowValue}", String.valueOf(i)))).click(); 
                findElement(By.xpath(("//tr[{rowValue}]" + text).replace("{rowValue}", String.valueOf(i)))).click();
                break;
            }
        }
    }

推荐答案

当您像您所拥有的那样编写break时,您只是中断了最本地的循环(在本例中是for(WebElement columnElement : columnElements)):

JVM真香系列 .java文件到.class文件

如果您为外部循环设置循环名称,如下所示

 loopName:
 for (int i = 1; i < tableSize; i++) {
 ....

然后您可以将其拆分,如以下代码所示:

loopName:
for (int i = 1; i < tableSize; i++) {       
    final List<WebElement> columnElements = tableRows.get(i).findElements(By.tagName("td"));
    for(WebElement columnElement : columnElements) {
        if(columnElement.getText().equalsIgnoreCase(alias)) {

            findElement(By.xpath(button.replace("{rowValue}", String.valueOf(i)))).click(); 
            findElement(By.xpath(("//tr[{rowValue}]" + text).replace("{rowValue}", String.valueOf(i)))).click();
            break loopName;
        }
    }
}

这将使您摆脱这两个循环,这似乎就是您所要求的。

 
精彩推荐