El Denari
El Denari

Reputation: 11

Can You Have A Return And A Formula In A Ternary?

   public boolean hasOne(int n) {
      while(n != 0) {
         (n % 10 == 1)? return true : n /= 10;

      }

      return false;
  }

I'm trying to check if there is a "1" in the number sent.

Upvotes: 1

Views: 74

Answers (2)

WJS
WJS

Reputation: 40034

No, you can't do that. A ternary operation is expected to return a value based on a condition. But a return statement does not return a value outside of it's normal behavior when returning from method calls. But to do what you want you can do the following:

public boolean hasOne(int n) {
   return Integer.toString(n).contains("1");
}

or

public static boolean hasOne(int n) {
    // in case it's negative
    n = Math.abs(n);

    while (n%10 > 1) {
        n/=10;
    }
    return  n == 1;
}

You can read about the Conditional Operator aka Ternary Operator here.

Upvotes: 0

passer-by
passer-by

Reputation: 1113

That makes no sense.

First of all, you have to understand the difference between a 'statement' and an 'expression'.

return is a statement, possibly containing an expression after the keyword.

The conditional operator (its proper name, not "the operator with three operands") is used in an expression.

What you have written is:

<expression> ?  <statement> : <expression>

-or-

<expression> ?  <statement> : <statement> 

(the second expression could be an expression statement).

There is no such syntax in Java. What you want is expressed with an 'if` statement, simply and clearly.

 if (n % 10 == 1)
     return true;
 else
     n /= 10;

An expression using the conditional operator is not interchangeable with an if-else statement.

Upvotes: 3

Related Questions