2013-08-04 65 views
9

我看過javadoc,但找不到與此相關的信息。停止在java中執行進一步的代碼

我想要應用程序停止執行一個方法,如果該方法中的代碼告訴它這樣做。

如果這句話是混亂的,這就是我想要的代碼做:

public void onClick(){ 

    if(condition == true){ 
    stopMethod(); //madeup code 
} 
    string.setText("This string should not change if condition = true"); 
} 

所以如果布爾「條件」爲真,方法「的onClick」已經停止執行進一步的代碼。

這只是一個例子。在我的應用程序中,還有其他一些方法可以幫助我完成工作,但如果這是可能的,那肯定會有所幫助。

+1

'條件= TRUE'是賦值表達式。注意區分。 –

+1

'(condition = true)'**總是**'true'。 – Maroun

+0

這只是一個例子。對於錯字感到抱歉。修復。 –

回答

26

只要做到:

public void onClick() { 
    if(condition == true) { 
     return; 
    } 
    string.setText("This string should not change if condition = true"); 
} 

這是多餘的寫if(condition == true),只寫if(condition)(通過這種方式,例如,你會不會寫=因爲失誤)。

2

你可以使用return結束方法的執行

1

從方法提早return;throw的例外。

除了完全退出過程外,沒有其他方法可以阻止進一步執行代碼。

5

有兩種方法來阻止電流的方法/過程:

  1. 引發異常。
  2. 即使它是無效方法返回值。

選項:你也可以殺死當前線程來停止它。

例如:

public void onClick(){ 

    if(condition == true){ 
     return; 
     <or> 
     throw new YourException(); 
    } 
    string.setText("This string should not change if condition = true"); 
} 
18

return出來方法的執行,break出來一個循環執行的和continue跳過當前循環的其餘部分。在你的情況,只是return,但如果你是在一個for循環,例如,做break停止循環或continue跳到下一步在環

+0

非常豐富。 –

2

要停止執行Java代碼只是使用這個命令:

System.exit(1); 

這個命令後,java立即停止!

例如:

int i = 5; 
    if (i == 5) { 
     System.out.println("All is fine...java programm executes without problem"); 
    } else { 
     System.out.println("ERROR occured :::: java programm has stopped!!!"); 
     System.exit(1); 
    } 
+0

'系統。exit()會停止整個服務器(在Tomcat上測試)或應用程序。 –