如何使用return
从if
语句中检索值?我不想立即返回,就像这样:java返回if语句
if(){
return "something";
}
这不是为我工作,如果return
是成功的方法返回,因为,但我需要返回,并返回完成时继续该方法中的操作。
如何使用return
从if
语句中检索值?我不想立即返回,就像这样:java返回if语句
if(){
return "something";
}
这不是为我工作,如果return
是成功的方法返回,因为,但我需要返回,并返回完成时继续该方法中的操作。
如果你想从一个方法来“回报”值,而实际上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;
}
}
+0:这是迄今为止最复杂的解决方案。 ;) – 2011-05-10 17:39:45
@downvoter - 据我了解这个问题:他/她想*发送*中间结果给调用者而没有实际离开方法。这与'return'不兼容(没有办法)。 – 2011-07-01 04:57:15
尝试类似:
String result = null;
if(/*your test*/) {
result = "something";
}
return result;
忘了埃尔,如果是在尝试 – user639285 2011-05-10 17:10:53
return
是方法。你可能想要这样的东西:
int foo;
if (someCondition) {
foo = 1;
} else {
foo = 2;
}
将你的字符串存储在一个变量。
String s = null;
if(somecondition) {
s = "something";
}
// do other stuff
return s;
使用finally块或将返回值保存到您在代码结尾处返回的变量中。
@ user639285,是在一个try语句中,最后是为您的具体情况而设计的。使用finally块。 – jzd 2011-05-10 17:24:39
你的意思是这样
String result = "unknown";
if(condition){
result = "something";
}
// do something.
return result;
这应该是最简单的方法
return yourCondition ? "ifTrue" : "ifFalse";
您应该只有一个函数的退出点。 IE,我不会建议在if语句中加入回报。 – user489041 2011-05-10 17:10:16
这个问题应该得到这么多即时重复答案的奖励:) – Preston 2011-05-10 17:10:39
@user不仅这是非常有争议的,它与此无关;他不想返回 – 2011-05-10 17:11:28