2012-11-26 40 views
0

我有一個方法,我在比較for循環內的arraylist值。 如果loop1的任何單個條件爲真,我不想執行Loop 2(請參閱下面的代碼)。如何避免循環外的執行代碼

現在,什麼happing是,對於一些值loop 1是statisfy和一些其他值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; 
} 
+0

爲什麼不簡單地使用return(或break)? – Rafael

+0

你的代碼對我來說似乎不清楚。第一個循環在哪裏結束? – CodeDreamer

+0

@codeDreamer at'return ERROR;' –

回答

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; 
     } 
+0

是的,你是對的。我也嘗試過。但我保持着'休息;返回ERROR; '。所以我是錯誤的。然後我終於想到這裏問。謝謝Ali ALamir –

+0

不客氣。 –

0

您應該使用break語句來實現這一點,或者你可以創建一個本地布爾變量,並用它來避免環路去2.

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

if(flag){ 
//loop 2 
}