我正在尝试实现一个返回布尔值true或false的方法。该方法根据if和else语句将布尔值isMatch初始化为true或false。
public class BooleanTest {
int num;
boolean isMatch;
public BooleanTest() {
num = 10;
}
public boolean isMatch() { //variable is already initialize to 10 from constructor
if (num == 10)
isMatch = true;
else
isMatch = false;
return isMatch;
}
public static void main(String[] arg) {
BooleanTest s = new BooleanTest();
System.out.println(s.isMatch);
}
}
isMatch的输出应该是true,但我得到的输出是isMatch是false。我的布尔方法是错误的吗,我该如何修复它?谢谢你的帮助。
首先,您的整个isMatch
方法最好折叠为:
public boolean isMatch() {
return num == 10;
}
其次,您现有的代码确实可以工作,除非您更改num
的值。您应该查看您使用的任何诊断来显示输出为false
……我怀疑他们误导了您。有没有可能您正在打印名为isMatch
的字段的值而不是调用该方法?这可以解释它。这就是为什么拥有与字段同名的方法是个坏主意的原因之一。此外,我建议将您的字段设为私有。
简短但完整的示例显示了工作方法调用和“失败”字段访问(工作正常,但没有做你想做的):
public class BooleanTest {
private int num;
private boolean isMatch;
public BooleanTest() {
num = 10;
}
public boolean isMatch() {
return num == 10;
}
public static void main(String[] args) {
BooleanTest test = new BooleanTest();
System.out.println(test.isMatch()); // true
System.out.println(test.isMatch); // false
}
}
老实说,不清楚你为什么会有这个领域——我会把它去掉。
你必须称之为
b.isMatch()
不像
b.isMatch
确保您在执行时使用大括号调用方法isMatch()
,否则您将引用字段isMatch
。应如下:
BooleanTest bt = new BooleanTest();
bt.isMatch(); // include () and not bt.isMatch
改变
System.out.println(s.isMatch);
到
System.out.println(s.isMatch());