user3353768
user3353768

Reputation: 147

Java illegal start of expression and 'else' without 'if' syntax errors

I'm getting the errors: illegal start of expression and 'else' without 'if' but can't find any syntax errors here.

    public int faultyMethod2(int a, int b) {
    int result;

    if((a == 0) || b > 0)) {
        result = (b / a);
    }
    else if (a < 0) {
        result = (a + b);
    }

    return result;
}

Upvotes: 0

Views: 149

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 122026

You just have a typo at if((a == 0) || b > 0)) { that should be if((a == 0) || (b > 0)) {. You missed a bracket.

And later on you need to have the default value of result. Either you can give the in declaration part or you need to provide an else part and give the default value there.

 public int faultyMethod2(int a, int b) {
    int result = 0;

    if((a == 0) || b > 0)) {
        result = (b / a);
    }
    else if (a < 0) {
        result = (a + b);
    }

return result;

}

or

 public int faultyMethod2(int a, int b) {
    int result;

    if((a == 0) || b > 0)) {
        result = (b / a);
    }
    else if (a < 0) {
        result = (a + b);
    }else {
       result = 0;
    }

    return result;
}

Upvotes: 1

Related Questions