boolean method trouble
java
Solution
Firstly, your entire `isMatch` method would be better collapsed to:
public boolean isMatch() {
return num == 10;
}
Secondly, your existing code really will work, unless you're changing the value of `num`. You should look at whatever diagnostics you're using to show the output as `false`... I suspect they're misleading you. Is it possible that you're printing out the value of the field called `isMatch` rather than calling the method? That would explain it. This is one reason why it's a bad idea to have a method with the same name as a field. Additionally, I'd recommend making your fields private.
Short but complete example showing both the working method call and the "failed" field access (working fine, but not doing what you want):
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
}
}
It's not clear why you've got the field at all, to be honest - I'd remove it.
Problem
Im trying to implement a method to return the boolean true or false. The method initializes the boolean isMatch to true or false based on the if and else statement. ``` 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); } } ``` The outprint of isMatch should be true, but i get the output isMatch is false. Is my boolean method wrong and how can i fix it? Thank you for your help.