Java ternary operator confusion -
here 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 got error when compiling
exception in thread "main" java.lang.error: unresolved compilation problems: syntax error on tokens, expression expected instead syntax error on token "]", delete token syntax error, insert "]" complete expression
and if change '<' '>' as
key > a[mid] ? hi = mid : lo = (mid + 1);
got total different error:
exception in thread "main" java.lang.error: unresolved compilation problem: syntax error on token ">", -> expected
i confused ternary operator usage in java. after all, code works fine in c++
the compiler having hard time parsing expression because used statement-expression.
since ternary operator expression, should not* used in place of statement. since control assignment, statement, condition, should use regular if
:
if (key < a[mid]) { hi = mid; } else { lo = (mid + 1); )
* in fact, java not allow ternary expressions used statements. work around issue wrapping expression in assignment or initialization (see demo), result in code hard read , understand, should avoided.
Comments
Post a Comment