Java ternary operator obfuscation
This is my code
public class BinarySearch { public static int binsearch(int key,int[] a) { int lo = 0; int hi = a.length - 1; while (lo < hi) { int mid = (lo + hi) >> 1; key < a[mid] ? hi = mid : lo = (mid + 1); } return lo--; } }
I encountered an error while compiling
Exception in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error on tokens,Expression expected instead Syntax error on token "]",delete this token Syntax error,insert "]" to complete Expression
If I change '<' to '>' such as
key > a[mid] ? hi = mid : lo = (mid + 1);
Got a completely different error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error on token ">",-> expected
I'm really confused about the use of ternary operators in Java After all, this code works well in C
Solution
It is difficult for the compiler to parse an expression because it is used like statement expression
Since the ternary operator is an expression, it should not be used instead of a statement Since you want to use conditions to control assignment (this is a statement), you should use the general if:
if (key < a[mid]) { hi = mid; } else { lo = (mid + 1); )
*In fact, Java does not allow ternary expressions to be used as statements You can solve this problem by wrapping expressions in assignment or initialization (see demo), but this will make the code difficult to read and understand, so it should be avoided