0
  1. Errors are illegal start of an expression
  2. error: not a statement
  3. ';' expected

I am receiving an error about my if else statement in takeStix().

private int numStix;

public int getNumStix() {return numStix;}

public boolean takeStix(int number) {
      ( number <= 3 && number <= getNumStix() ) ? return true : return false;
}

2 Answers 2

6

You can't put statements (like return true) in the ternary operator, only values.

So you could put:

return (number <= 3 && number <= getNumStix()) ? true : false;

But you don't even need a ternary operator for this:

public boolean takeStix(int number) {
    return (number <= 3 && number <= getNumStix());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Is this a Java only rule? I tend to do this in my JavaScript is this a bad practice?
1

In your case, as @khelwood has shown, you don't need a ternary expression. In general, however, the format for using a ternary expression in a return statement should be

return boolean_condition ? something : something_else

For example,

public boolean takeStix(int number) {
    return number <= Math.min(3, getNumStix()) ? true : false;
}

4 Comments

Thank you that makes more sense.
Is this a Java only rule? I tend to do this in my JavaScript is this a bad practice?
In general, it is a better practice to avoid ternary expressions when a simple boolean assignment suffices. I am no expert in JavaScript, but this discussion might be useful for you: stackoverflow.com/questions/19439219/…
Ahhh I understand it now. Since the condition itself is a Boolean it will generate true or false regardless. Thank you, this will help my programming tremendously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.