Skip to content
Advertisement

Java ternary operator on simple binary search problem

How can I refactor this code to NOT include “int ans =” I’d like to keep the ternary operator. Since int ans is not actually the answer it makes no sense to keep it this way.

What would be the correct way to use the ternary operator to change the left / right values?

JavaScript

Advertisement

Answer

The conditional operator can only be used as part of an expression. An expression cannot stand on its own, but needs to be part of a statement. Assigning a variable is a statement. Computing a value and not storing it, is not. Convert the expression to an statement:

JavaScript

Becomes:

JavaScript

If you want to save a few key strokes:

JavaScript

Relevant links to the JLS:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement