什么是'?'在代码中

时间:2014-07-30 08:48:44

标签: java android ternary-operator

有人可以解释这些代码吗?为什么它有?

package course.examples.theanswer;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TheAnswer extends Activity {

public static final int[] answers = { 42, -10, 0, 100, 1000 };
public static final int answer = 42;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.answer_layout);

    TextView answerView = (TextView) findViewById(R.id.answer_view);


    int val = findAnswer();
    String output = (val == answer) ? "42" : "We may never know";
    answerView.setText("The answer to life, the universe and everything is:\n\n"
                    + output);
}

private int findAnswer() {
    for (int val : answers) {
        if (val == answer)
            return val;
    }
    return -1;
}
}

6 个答案:

答案 0 :(得分:7)

条件/三元运算符。

String output = (val == answer) ? "42" : "We may never know";

实际上与:

相同
if(val==answer)
{
 output = "42" 
}

else
{
output = "we may never know"
}

答案 1 :(得分:1)

这称为Ternary operator。这是if-else陈述的一种替代。

(Condition) ? {if true execute this} : {else do this}

答案 2 :(得分:1)

这是一个三元运营商..

这一行:

String output = (val == answer) ? "42" : "We may never know";

与此相同:

String output;
if (val == answer) {
  output = "42";
} else {
  output = "We may never know";
}

它通常用于简单的条件和作业......单行。

答案 3 :(得分:1)

?:if-then-else行为的操作符

(val == answer) ? "42" : "We may never know";

这意味着

if(val==answer) {
    output = "42"
} else { 
     output = "We may never know";
} 

答案 4 :(得分:1)

如果你的意思是这一行:

String output = (val == answer) ? "42" : "We may never know";
    answerView.setText("The answer to life, the universe and everything is:\n\n"
                    + output);

?是(if ... then ... else)的缩写形式。

if(val == answer)then output =“42”else output =“我们可能永远不会知道”;         answerView.setText(“生命的答案,宇宙和一切都是:\ n \ n”                         +输出)

答案 5 :(得分:1)

在这一行

String output = (val == answer) ? "42" : "We may never know";

?代表三元运算符:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

如果val == answer为true,则分配给输出的值将为" 42"。如果它等于假,它将被分配"我们可能永远不会知道"

val = answer;
...
String output = (val == answer) ? "42" : "We may never know";
System.out.println(output);

会输出:

  

42

,而:

val = answer + 1;
...
String output = (val == answer) ? "42" : "We may never know";
System.out.println(output);

会输出:

  

我们可能永远不会知道