0

我有一个方法,我在 for 循环中比较 arraylist 值。Loop 2如果 loop1 的任何单个条件为真,我不想执行(见下面的代码)。

现在发生了什么,对于某些值loop 1loop 2statisfy 而对于其他一些值是满意的。因此,我是 db 填充了错误的数据。

我想以这样的方式修改我的代码。如果任何数组列表值符合要求,loop 1则编译器应从return ERROR. 之后它不应该执行代码。

循环检查条件为if(quant>Integer.parseInt(book.getQuantity()))

动作.java。

    public String execute()
{   
      if(id.length == quantity.length)
    {
      for (int i = 0; i < id.length; ++i)
       { 
         book = dao.listbookdetailsByBId(id[i]);
         Double dq=new Double(quantity[i]);
         int quant=dq.intValue();  
          if(quant>Integer.parseInt(book.getQuantity()))
          {   
                 //Loop 1  , this is executing if any of the quant is greater then book.getQuantity()..                    
                //i want to stop executing LOOP2 ,if any of the value of quant is greater then book.getQuantity().
              addActionError("You have entered an invalid quantity for the Book Title- ''"+book.getBookTitile()+"''."); 
              return ERROR; 
          }   

    /*  Loop2 starts here
    *   Loop 2 , this is executing if any of the quant is lesser .. 
    *   The below code should execute only if compiler does not reach to the loop1 */

                      // Some DAO code goes here

       }
    }

    return SUCCESS;
}
4

2 回答 2

1

只需使用 break 语句

if(quant>Integer.parseInt(book.getQuantity()))
      {   
             //Loop 1  , this is executing if any of the quant is greater then book.getQuantity()..                    
            //i want to stop executing LOOP2 ,if any of the value of quant is greater then book.getQuantity().
          addActionError("You have entered an invalid quantity for the Book Title- ''"+book.getBookTitile()+"''."); 
          break; 
      }
于 2012-11-26T20:12:51.693 回答
0

您应该使用 break 语句来实现这一点,或者您可以创建一个局部布尔变量并使用它来避免进入循环 2。

    if(quant>Integer.parseInt(book.getQuantity()))
          { flag=false;
}

if(flag){
//loop 2
}
于 2012-11-26T20:15:11.470 回答