2011-05-10 167 views
1

如何使用returnif語句中檢索值?我不想立即返回,就像這樣:java返回if語句

if(){ 
return "something"; 
} 

這不是爲我工作,如果return是成功的方法返回,因爲,但我需要返回,並返回完成時繼續該方法中的操作。

+0

您應該只有一個函數的退出點。 IE,我不會建議在if語句中加入回報。 – user489041 2011-05-10 17:10:16

+1

這個問題應該得到這麼多即時重複答案的獎勵:) – Preston 2011-05-10 17:10:39

+5

@user不僅這是非常有爭議的,它與此無關;他不想返回 – 2011-05-10 17:11:28

回答

1

如果你想從一個方法來「回報」值,而實際上return從消息ING,那麼你必須定義在調用類的setter方法,並給他們打電話,像這樣:

public class Caller { 

    private boolean someState; 

    // ... 

    public void doSomething() { 
     // the method call 
     Worker w = new Worker(this); 
     int result = w.workForMe(); 
    } 

    public void setState(boolean state) { 
     this.someState = state; 
    } 

} 

而且Worker

public class Worker { 

    private Caller caller; 

    public Worker(Caller caller) { 
     this.caller = caller; 
    } 

    public int workForMe() { 
     // now the conditions: 
     if(clearBlueSky) { 
      // this emulates a "return" 
      caller.setState(true); 
     } 
     // this returns from the method 
     return 1; 
    } 

} 
+3

+0:這是迄今爲止最複雜的解決方案。 ;) – 2011-05-10 17:39:45

+0

@downvoter - 據我瞭解這個問題:他/她想*發送*中間結果給調用者而沒有實際離開方法。這與'return'不兼容(沒有辦法)。 – 2011-07-01 04:57:15

9

嘗試類似:

String result = null; 

if(/*your test*/) { 

    result = "something"; 

} 

return result; 
+0

忘了埃爾,如果​​是在嘗試 – user639285 2011-05-10 17:10:53

0

return是方法。你可能想要這樣的東西:

int foo; 

if (someCondition) { 
    foo = 1; 
} else { 
    foo = 2; 
} 
2

將你的字符串存儲在一個變量。

String s = null; 
if(somecondition) { 
    s = "something"; 
} 
// do other stuff 
return s; 
0

使用finally塊或將返回值保存到您在代碼結尾處返回的變量中。

+0

@ user639285,是在一個try語句中,最後是爲您的具體情況而設計的。使用finally塊。 – jzd 2011-05-10 17:24:39

0

你的意思是這樣

String result = "unknown"; 
if(condition){ 
    result = "something"; 
} 
// do something. 
return result; 
2

這應該是最簡單的方法

return yourCondition ? "ifTrue" : "ifFalse";