2015-06-19 42 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(); 
  • 有使用反射,但在解決方法一天結束時,代碼的簡潔性不會超過可讀性。