我查看了Javadoc,但找不到与此相关的信息。
如果该方法中的代码告诉它,应用程序停止执行方法。
如果这句话令人困惑,这就是我想在我的代码中做的事情:
public void onClick(){
if(condition == true){
stopMethod(); //madeup code
}
string.setText("This string should not change if condition = true");
}
因此,如果布尔值condition
为真,则方法onClick
必须停止执行更多代码。
这只是一个例子。还有其他方法可以让我在我的应用程序中完成我想要完成的任务,但如果可行,那肯定有帮助。
答案 0 :(得分:33)
只是做:
public void onClick() {
if(condition == true) {
return;
}
string.setText("This string should not change if condition = true");
}
写if(condition == true)
是多余的,只需写if(condition)
(这样,例如,你不会错误地写=
。)
答案 1 :(得分:19)
return
退出方法执行,break
退出循环执行,continue
跳过剩余的当前循环。在您的情况下,仅return
,但如果您处于for循环中,请执行break
停止循环或continue
跳转到循环中的下一步
答案 2 :(得分:6)
有两种方法可以阻止当前的方法/过程:
选项:你也可以杀死当前线程来阻止它。
例如:
public void onClick(){
if(condition == true){
return;
<or>
throw new YourException();
}
string.setText("This string should not change if condition = true");
}
答案 3 :(得分:6)
要停止执行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);
}
答案 4 :(得分:3)
您可以使用return
结束方法的执行
答案 5 :(得分:2)
早期方法中的return;
或throw
例外。
除了完全退出流程外,没有其他方法可以阻止执行进一步的代码。