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;
}
Rafael
  • 7,605
  • 13
  • 31
  • 46

2 Answers2

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());
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
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;
}
Chthonic Project
  • 8,216
  • 1
  • 43
  • 92
  • Thank you that makes more sense. – Rafael Dec 03 '14 at 21:45
  • Is this a Java only rule? I tend to do this in my JavaScript is this a bad practice? – Rafael Dec 03 '14 at 21:48
  • 1
    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: http://stackoverflow.com/questions/19439219/ternary-operator-with-return-statements-javascript – Chthonic Project Dec 03 '14 at 21:50
  • 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. – Rafael Dec 03 '14 at 21:53