我有一个问题...... 今天我做了类(class)和方法。 制定方法后,我发现一个错误。 这是“我如何使用‘return’?”。
哪些代码是错误的? 我没有发现问题。
public boolean locking(){
if (false)
System.out.print("Open the door");
return false;
else
System.out.print("Now lock the door");
return true; //<- how can i express 'return'?
}
最佳答案
此代码缺少括号。因此第一个 if
仅引用第一个 System.out
,而不是 return
。
尝试以下操作:
public boolean locking() {
if (false) {
System.out.print("Open the door");
return false;
} else {
System.out.print("Now lock the door");
return true;
}
}
编辑:请记住,上面代码中定义的 if 条件绝对没有意义。因此,请确保您始终进行比较,否则您将始终得到相同的结果。
了解使用 return 语句将退出该方法也很重要,这意味着 return
下面的任何代码都不会被执行。这允许您省略 if 语句的 else
部分。因为当条件满足时,将执行第一个 return 并离开该方法,当不满足条件时,代码将继续执行唯一的其他可能性。这使得代码变得更轻,但在使用多个 if 语句时要注意。
public boolean locking() {
if (false) {
System.out.print("Open the door");
return false;
}
System.out.print("Now lock the door");
return true;
}
关于java - 我不明白java中的 'return of if statement',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34806449/