[英]How do I check if a method returns true or false in an IF statement in Java?
假设我有一个布尔方法,它使用if语句来检查返回类型是true还是false :
public boolean isValid() {
boolean check;
int number = 5;
if (number > 4){
check = true;
} else {
check = false;
}
return check;
现在,我想在另一个方法中使用此方法作为if语句的参数:
if(isValid == true) // <-- this is where I'm not sure
//stop and go back to the beginning of the program
else
//continue on with the program
基本上我要问的是,如何在if语句的参数中检查布尔方法的返回类型是什么? 非常感谢您的回答。
因为它是一种方法,所以要调用它之后你应该使用parens,这样你的代码就会变成:
if(isValid()) {
// something
} else {
//something else
}
public boolean isValid() {
int number = 5;
return number > 4;
}
if (isValid()) {
...
} else {
...
}
您应该能够在IF条件下调用该函数,以便:
if (isValid()) {
}else {
}
由于isValid()
返回一个boolean
因此将立即评估条件。 我听说在你测试条件之前创建一个局部var是更好的形式。
boolean tempBoo = isValid();
if (tempBoo) {
}else {
}
- If
语句只接受 boolean
值。
public boolean isValid() {
boolean check = false; // always intialize the local variable
int number = 5;
if (number > 4){
check = true;
} else {
check = false;
}
return check;
}
if(isValid()){
// Do something if its true
}else{
// Do something if its false
}
if (isValid()) {
// do something when the method returned true
} else {
// do something else when the method returned false
}
您可以使用 :
if(isValid()){
//do something....
}
else
{
//do something....
}
public boolean isValid() {
boolean check;
int number = 5;
if (number > 4){
check = true;
} else {
check = false;
}
return check;
如果没有布尔检查,你怎么能做这整个方法?
那么如何摆脱.. check = true,check = false,返回检查东西?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.