Java 布尔方法故障
我正在尝试实现一个返回布尔值true或false的方法。该方法基于if和else语句将布尔isMatch初始化为true或falseJava 布尔方法故障,java,Java,我正在尝试实现一个返回布尔值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 co
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 {
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 st[])//test your code in main..
{
BooleanTest bt = new BooleanTest();//constructor of BooleanTest is called
System.out.println(bt.isMatch());//Check the value returned by isMatch()
}
}
EDIT
您编辑的帖子显示,在
main
中,您正在打印isMatch
,而不是isMatch()
,默认情况下,false
。。您应该改用isMatch()
。确保在执行时使用大括号调用方法isMatch()
,否则您将引用字段isMatch
。应如下所示:
BooleanTest bt = new BooleanTest();
bt.isMatch(); // include () and not bt.isMatch
改变
System.out.println(s.isMatch);
到
你必须这样称呼它
b.isMatch()
不像
b.isMatch
您可以在代码中发布如何调用此方法吗?显示您的
main()
方法。您的代码很好,问题在别处。你能发布你的调用类和BooleanTest的完整代码吗?我建议你将函数重命名为不同的名称。我已经编辑了这个程序。请看一看。谢谢,谢谢。这可以解决我的问题。
b.isMatch()
b.isMatch