IndexOutOfBoundsException交付Java

时间:2013-12-11 06:13:32

标签: java indexoutofboundsexception

请找到我的代码

public ArrayList<String> addtocartdisabled() {
    ArrayList<String> checkbox_property = new ArrayList<String>();
    WebElement portfoliotable = cpi.tbl_portfolio;
    List<WebElement> allRows = portfoliotable
            .findElements(By.tagName("tr"));
    String rowvalue = "";

    for (int row = 1; row < allRows.size(); row++) {
        String Incart = driver
                .findElement(
                        By.xpath("//*[@id='tblPortfolio']/tbody/tr[" + row
                                + "]/td[9]")).getText().trim();

        if (Incart.equals("In Cart")) {
            rowvalue = Integer.toString(row);
            checkbox_property.add(rowvalue);
            break;
        }
    }
    return checkbox_property;
}

另一种方法将收到此方法的返回值(addtocartdisabled)

public ArrayList<String> patentportfolio_scrapwithoutaddtoCart()
        throws InterruptedException {
    ArrayList<String> Actual_result = addtocartdisabled();
    String addtocartrecord = Actual_result.get(0);
    }

执行期间addtocartdiasbled方法在这种情况下不会返回任何值,我们会收到"IndexOutOfBoundsException: Index: 0, Size: 0"

让我知道我们如何处理此异常

2 个答案:

答案 0 :(得分:0)

因为addtocartdisabled()方法可能会返回空List,因为您在if (Incart.equals("In Cart")) {的条件下添加了值,这可能始终为false。要避免此异常,您可以清空ArrayList

public ArrayList<String> patentportfolio_scrapwithoutaddtoCart()
    throws InterruptedException {
  ArrayList<String> Actual_result = addtocartdisabled();

  if(!Actual_result.isEmpty()){
   String addtocartrecord = Actual_result.get(0);
  }
}

答案 1 :(得分:0)

Actual_result.get(0)假设您至少有一个元素存在。

如果您的Incart永远不会满足,那么您将永远不会拥有任何内容

String Incart = driver.findElement(By.xpath("//*[@id='tblPortfolio']/tbody/tr[" + row + "]/td[9]")).getText().trim();

这就是您收到错误的原因。