简体   繁体   中英

Java Ternary Operator Error

  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;
}

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());
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM