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.
CodePudding user response:
You can't do that. Why not do
return Integer.toString(n).contains("1");
CodePudding user response:
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.