Astrum Astrum - 3 months ago 10
Java Question

Java error "missing return statment"

So here's my code:

public class Bob {

public static int F(int n) {
if (n > 1) {
if (n % 2 == 0) {
n = n / 2;
System.out.println(n);
return F(n);
} else if (n % 2 != 0) {
n = 3 * n + 1;
System.out.println(n);
return F(n);
} else {
System.out.println("Complete");
return 0;
}
}


public static void main(String[] args) {
int result = F(10);
System.out.println(result);
}
}


I can't seem to find where the error is. All the possible values of n are covered. If I add a simple return value outside of the if-statment, it will work, but I don't see why that should be the case.

Also, I'd like to add a print "i" statement into main, but whenever I do something like:

if (something){
int i;
i++;
do something


I try to add a System.out.println(i) and it gives me an error about a static variable.

ajb ajb
Answer

Your code makes no sense, as posted. You have an if/else statement with three branches. The first branch is executed if n%2 is 0. The second branch is executed if n%2 is not zero. Since that covers all the possibilities, when is the third branch supposed to be executed?

Because this doesn't make sense (and because I've seen this coding problem before), I suspect that you meant the third branch to be executed if the first if is false, i.e. if n <= 1. But because of the curly braces, the compiler attaches the "else" to the if (n%2...) branches, not to if (n > 1). To fix this, you need another curly brace:

public static int F(int n){
    if (n > 1){             // ***** Opening brace 1
        if (n%2 == 0){
            n = n/2;
            System.out.println(n);
            return F(n);
        } else if(n%2 != 0){  // ***** Opening brace 2
            n = 3*n+1;
            System.out.println(n);
            return F(n);
        }            // This curly brace matches "opening brace 2"
    }                // This curly brace matches "opening brace 1"
    else {
        System.out.println("Complete");
        return 0;
    }
}

But that still isn't legal, and the reason isn't obvious. What happens here is that Java requires that you have a return statement in every possible path. And here's what the compiler thinks: If n > 1, then you have an if statement if (n%2 == 0). If this fails, it goes to the if statement if (n%2 != 0). If this is also false, then it will drop down past the last else part, and it will get to the end of the method without returning anything.

Of course, you and I will look at it and say, that's impossible, because either n%2 == 0 or n%2 != 0 must be true. But that requires that we do some reasoning. Java compilers don't do that kind of reasoning, so it can't tell that one of those two if expressions must be true.

So fixing this also requires that you change

        } else if(n%2 != 0) { 

to

        } else {

You don't need the if anyway--it's totally redundant. If we get here, we already know that n%2 != 0.