Java ternar confusion

here 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 got 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

      

and if i change '<' to '>' like

key > a[mid] ? hi = mid : lo = (mid + 1);

      

got a generic error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Syntax error on token ">", -> expected

      

I am really confused about using the ternary operator in java. in the end this code works fine in C ++

+3


source to share


4 answers


The compiler is having a hard time parsing your expression because it is being used as an expression expression.

Since the ternary operator is an expression, it should not be used instead of the * operator . Since you want to control the assignment, which is an expression, with a condition, you should use the usual one if

:



if (key < a[mid]) {
    hi = mid;
} else {
    lo = (mid + 1);
)

      

* In fact, Java does not allow term expressions to be used as operators. You can work around this problem by wrapping your expression in an assignment or initialization (see demo ), but this will result in code that is difficult to read and understand and should therefore be avoided.

+11


source


The ternary operator in java only works like this:

x=(a>b?a:b);

      

This operation puts more a

and it b


is not allowed:

a>b?x=a:x=b;

      



It may be similar, but ternary statement branches in java can only hold a value, not an assignment


EDIT:
In your case, I advise using the instructionif

+1


source


In this case, you must use an if statement.

if(key > a[mid])
    hi = mid;
else
    lo = mid + 1;

      

This is because the ternary operator is used when you set a variable. For example:

foo = (firstVariable > secondVariable) ? 1 : 0;

      

(something along these lines).

+1


source


From the documentation :

The conditional operator has three operand expressions. ? appears between the first and second expressions, and : appears between the second and third expressions.

The first expression must be of type boolean or Boolean, or a compile-time error occurs.

It is a compile-time error for the second or third operand expression as a void method call.

In other words, the conditional operator cannot be used to do something like this *:

key < a[mid] ? foobar1() : foobar2();

      

  • There is a workaround that uses reflection, but in the end, the brevity of the code doesn't trump readability.
0


source







All Articles