2013-10-31 37 views
-1

我想打破其他條件,如果它有一個內部if條件,如果內部條件如果內部如下變成真,請給我建議一種方式。如何打破其他條件如果條件

if(condition1=true){ 

     } 
    else if(condition2=true){ 

      if(condition3=true){ 

       do activity 1; 
       //I want to break here if condition3 is true, without executing activity 2 & 3 
      } 

      do activity 2; 
      do activity 3; 

    } 
+3

使用return; ... –

+0

我希望'='是該示例的目的,而不是代替''==(應該根本不存在)。 – Maroun

+0

@MarounMaroun只是'if(conditionN)' – nachokk

回答

5
else if(condition2){ 
     if(condition3){ 
       do activity 1; 
       //I want to break here if condition3 is true, without executing activity 2 & 3 
     } 
     else 
     { 
       do activity 2; 
       do activity 3; 
     } 
} 
1

在Java中,你只能在循環forwhileswitch/case或命名塊

使用break不過你,如果你有方法void你可以寫return;

喜歡的東西:

void foo(){ 

if(condition1=true){ 

     } 
    else if(condition2=true){ 

      if(condition3=true){ 

       do activity 1; 

       return; 
      } 

      do activity 2; 
      do activity 3; 

    } 
} 
+0

真的,強大的'return'將結束方法的執行。如果if後面沒有邏輯,這將是一個有效的選項。 – Gamb

+0

「在java中,您只能在循環中使用break或while或switch/case。」錯誤。你也可以從命名模塊中分離出來。 – Smallhacker

+0

@Smallhacker你能舉個例子嗎?或參考? –

0

那麼,你可以去一個else聲明。

... 
if(condition3=true){ 
    do activity 1; 
} else { 
    do activity 2; 
    do activity 3; 
} 
... 

或者,如果你願意,你可以的代碼,整個塊中提取到一個單獨的功能,並已將其活動後權限返回1.

我想你也可以使用一個命名塊:

... 
doActivities:{ 
    if(condition3=true){ 
     do activity 1; 
     break doActivities; 
    } else { 
     do activity 2; 
     do activity 3; 
    } 
} 
... 

但是,這危險地接近完全轉到並且可能不被推薦。

1

其他人已經回答了重組塊。如果檢查的條件不需要按順序發生,你可以做 -

if(condition3=true){ 
    do activity 1; 
} else if(condition2=true){ 
    do activity 2; 
    do activity 3; 
} else if(condition1=true){ 

} 
0

沒有需要休息。這應該做到這一點。

if(condition1=true){ 

} else if(condition2=true){ 
    if(condition3=true){ 
     do activity 1; 
     //I want to break here if condition3 is true, without executing activity 2 & 3 
    } else { 
     do activity 2; 
     do activity 3; 
    } 
} 
0

事實上,我會嘗試更易於閱讀的方式:

if(condition1) 
{ 

} 
else if(condition2 && condition3) { 
     do activity 1; 

} 
else if(condition2 && !condition3) { 
     do activity 2; 
     do activity 3; 
} 

這樣你避免嵌套IFS,並保持你的代碼非常容易閱讀。

0

像這樣的其他模式強烈暗示有一些類結構來處理這些情況。

Activity activity = ActivityFactory.getActivity(conditionCause); 
activity.execute();