2015-06-19 39 views
3

是我的代码的Java三元操作混乱

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--; 

    } 
} 

编译

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 

当我得到一个错误,如果我改变 '<' 到 '>' 作为

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

有一个总不同的错误:

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

我真搞不清楚在Java三元运算符的使用。 毕竟,这个代码在C++中工作正常

+0

您可以先将您的代码分解为非三元if语句吗?我向你保证java中的三元作品,但你在这里写的不是java代码。 –

+0

这不是特定于三元运算符。在Java中,与C不同,不能将表达式放置在需要语句的位置。 – Holger

+1

“这段代码可以在C++中正常工作”这是因为C++对于语句表达式要轻松得多。另一方面,Java只允许将直接和复合赋值表达式用作语句。 – dasblinkenlight

回答

11

编译器很难分析你的表达式,因为它的使用就像一个语句表达式。

因为三元运算符是一个表达,它不应该*来代替声明的使用。既然你想控制的分配,这是一个声明,条件,你应该使用常规的if

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

*事实上,Java不允许三元表达式中使用的语句。你可以通过在一个赋值或初始化中包装你的表达式来解决这个问题(参见demo),但是这会导致难以阅读和理解的代码,所以应该避免。

1

在Java三元操作符只能是这样的:

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

这个操作将的a较大和b
这是不允许的:

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

它也许看起来相似,但三元java中的运算符分支只能包含值,不能分配


编辑:
在你的情况下,我建议使用 if声明

1

在这种情况下,你应该使用if语句。

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

这是因为三元运算符用于设置变量时。例如:

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

(沿着这些线)。

0

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 either the second or the third operand expression to be an invocation of a void method.

换句话说,有条件的经营者不能被用来做这样的事情*:

key < a[mid] ? foobar1() : foobar2(); 
  • 有使用反射,但在解决方法一天结束时,代码的简洁性不会超过可读性。