Techn0mancer Techn0mancer - 3 years ago 137
Java Question

else statement with no if condition isn't default

public int compareTo(Tool b)
{
if(cost > b.cost)
return 1;
else if(cost == b.cost)
{
if(name.compareTo(b.name) < 0)
return 1;
else if(name.compareTo(b.name) == 0)
return 0;
else if(name.compareTo(b.name) > 0)
return -1;
}
else
return -1;
}


NetBeans gives an error at the last brace because "missing return statement". This is solved if I remove the "else", but shouldn't
return -1
be the default codepath?

Answer Source

You don't have an else statement in your else if block. The compiler isn't smart enough to realize that <, ==, and > covers all cases. Removing the if(name.compareTo(b.name) > 0) would fix the issue.

public int compareTo(Tool b)
{
    if(cost > b.cost)
        return 1;
    else if(cost == b.cost)
    {
        if(name.compareTo(b.name) < 0)
            return 1;
        else if(name.compareTo(b.name) == 0)
            return 0;
        else if(name.compareTo(b.name) > 0)
            return -1;
        // You need an else here
    }
    else
        return -1; 
}

It must have a return statement for every possible branch (even if you know what it doesn't - that it isn't possible).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download