0

I'm expecting isCorrect() method to return "true", because it should have all the conditions to reach that answer, but it only return "false" (many times at that according to the console). There are errors but I have no idea what they are. Please tell me what's going so wrong with this code.

public class BooleanMethodTest {    
    static int num1 = 1;
    static int num2 = 2;
    static int num3 = 3;

    public static void main(String[] args) {    
        // it should print "true" but I get "false" instead
        System.out.println(isCorrect("s1"));
    }

    public static boolean isCorrect(String s) {
        boolean answer = false;
        // step 1
        if (s.equals("s1")) {
            if (num1 == 1) {
                isCorrect("s2");
            } else {
                System.out.println("else1");
            }
        }
        // step 2
        else if (s.equals("s2")) {
            if (num2 == 2) {
                isCorrect("s3");
            } else {
                System.out.println("else2");
            }
        }
        // step 3
        else if (s.equals("s3") ) {
            if (num3 == 3) {
                answer = true;
                return true;
            } else {
                System.out.println("else3");
            }
        }
        System.out.println(answer);
        return answer;
    }
}

Note on the duplicate

After exchanging all String comparisons with String#equals the problem still persists. So the linked duplicate does not solve the issue. However, the real issue was found, see the comment section.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Neo
  • 53
  • 2
  • 8
  • @rgettman, thanks for the recommendation. I edited it as you suggested but I don't think that was the problem. Would someone look at it again? – Neo Feb 21 '18 at 21:37
  • So after replacing all `String` comparisons with `String#equals` the problem has not resolved? – Zabuzard Feb 21 '18 at 21:44
  • 3
    It's rather easy. You only return something different in case `s3`. But the caller of case `s3` which is case `s2` does not capture the returned value, it instead throws it away: `isCorrect("s3");` without some kind of `boolean result = isCorrect("s3");`. Therefore, the first call `s1` has `answer = false` unchanged. So `s1` and `s2` will always return `false`, only `s3` returns `true`. But they will always call all the other variants. – Zabuzard Feb 21 '18 at 21:47
  • The problem is that I initiate the boolean answer inside the method. It's solved. Thank you for taking a look at my messy code. – Neo Feb 21 '18 at 21:48
  • 1
    Yes, the variable is local to the method. Multiple calls of the method all have different `answer` variables. They won't affect each other. – Zabuzard Feb 21 '18 at 21:48

0 Answers0