0
public int factorial(int number)
        {
            number <= 0 ? return 1 : return number * factorial(number - 1);
        }

The compiler tells me to that the first return is an invalid expression and there is a ; and } expected what should I do?

yui
  • 1
  • 1
  • Typo, move both `return` keywords before `number` (so there's only one `return` keyword). – gunr2171 Mar 09 '22 at 02:55
  • Thank you so much, the errors are gone but should I keep the `1` after the condition or there is a better code I can replace it with in case the condition is true? – yui Mar 09 '22 at 03:03
  • `return` is a "statement". The ternary operator `? :` is an "expression". An expression can have a value, and can contain other expressions. But a statement must stand alone. https://stackoverflow.com/questions/19132/expression-versus-statement – Jeremy Lakeman Mar 09 '22 at 03:15

1 Answers1

0

You're using the ternary operator incorrectly. You can't use return.

You actually want this:

return number <= 0 ? 1 : number * factorial(number - 1);

Docs:

condition ? consequent : alternative

The condition expression must evaluate to true or false. If condition evaluates to true, the consequent expression is evaluated, and its result becomes the result of the operation. If condition evaluates to false, the alternative expression is evaluated, and its result becomes the result of the operation. Only consequent or alternative is evaluated.

This means that consequent and alternative should both evaluate to values that can be returned.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86