如何避免执行循环外的代码

时间:2012-11-26 20:05:29

标签: java for-loop

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

现在有什么好处,因为某些值loop 1是完全正确的,而其他一些值loop 2是满足的。因此我觉得db填充了错误的数据。

我想以这样的方式修改我的代码。如果任何数组列表值满足loop 1,则编译器应从return ERROR返回。在此之后它不应该执行代码。

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

Action.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;
}

2 个答案:

答案 0 :(得分: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; 
      }

答案 1 :(得分:0)

您应该使用break语句来实现此目的,或者您可以创建一个本地布尔变量并使用它来避免进入循环2。

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

if(flag){
//loop 2
}