2013-03-17 6 views
10

説明: compareCharはtrueまたはfalseを返します。 trueの場合はボタンの値を設定し、falseの場合は何もしません。インラインifステートメントjava、なぜ動作していません

私は使用しようとしています: if compareChar(curChar、toChar( "0"))? getButtons().get(i).setText( "§");

NetBeansは言っている: は ')' を除外 ':':、

if compareChar(curChar, toChar("0")) ? getButtons().get(i).setText("§"); 
if compareChar(curChar, toChar("0")) ? getButtons().get(i).setText("§") : ; 
if compareChar(curChar, toChar("0")) ? getButtons().get(i).setText("§") : 

if (compareChar(curChar, toChar("0"))) ? getButtons().get(i).setText("§"); 
if (compareChar(curChar, toChar("0"))) ? getButtons().get(i).setText("§") : ; 
if (compareChar(curChar, toChar("0"))) ? getButtons().get(i).setText("§") : 

答えて

15

三項演算子? :が値を返すことですありがとう、私はこれらの組み合わせを試してみました

を除外フロー制御に ifを使用する場合は使用しないでください。

if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§"); 

は十分に機能します。 "あれば"、あなたのケースでは

if (cond) 
    statementA 
else 
    statementB 

、あなただけのすべてを削除することがあります。

http://java.about.com/b/2009/06/06/java-term-of-the-week-ternary-operator.htm

+0

「場合」を出したままにギヨームありがとう、これは利用可能な答えを理解するのが最も簡単です。.. –

0
cond? statementA: statementB 

はに等しいです。 ?:の代わりにif-elseを完全に使用するとします。一緒に混ぜないでください。

30

構文は以下の通りです:

"your condition"? "step if true":"step if condition fails" 
+2

を働きました。良くやった。 – JoeyG

15

(インラインの場合)Javaで使用している場合は動作しません声明「もし」..右の構文は、次の例である:

int y = (c == 19) ? 7 : 11 ; 

または

String y = (s > 120) ? "Slow Down" : "Safe"; 
System.out.println(y); 

あなたは、変数Yの型は戻り値と同じである見ることができるように...

あなたのケースでは、通常のif文を使用する方が良いです。

if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§"); 
0

(条件)?真の文:虚偽の陳述

+1

この質問は3年前に尋ねられ、答えられました。これは余分な情報を追加するものではありません。 – George

関連する問題