什么是问号“?”和冒号“:”运算符用于?

时间:2012-04-26 15:48:06

标签: java operators ternary-operator conditional-operator

关于使用问号的两个问题“?”和打印函数括号内的冒号“:”运算符:它们做了什么?此外,是否有人知道他们的标准术语或我可以在哪里找到有关其使用的更多信息?我读过它们与“if”'else'语句类似。

int row = 10;
int column;
while (row >= 1)
{
    column = 1;
    while(column <= 10)
    {
        System.out.print(row % 2 == 1 ? "<" : "\r>");
        ++column;
    }
    --row;
    System.out.println();
}

7 个答案:

答案 0 :(得分:269)

这是ternary conditional operator,可以在任何地方使用,而不仅仅是print语句。它有时被称为“三元运算符”,但it's not the only ternary operator只是最常见的运算符。

以下是维基百科展示其运作方式的一个很好的例子:

  

编写了C,Java和JavaScript中的传统if-else结构:

if (a > b) {
    result = x;
} else {
    result = y;
}
     

这可以改写为以下声明:

result = a > b ? x : y;

基本上它采用以下形式:

boolean statement ? true result : false result;

因此,如果布尔语句为真,则获得第一部分,如果为假,则获得第二部分。

如果仍然没有意义,请尝试这些:

System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");

答案 1 :(得分:8)

这是一个等同于

的if / else语句
if(row % 2 == 1){
  System.out.print("<");
}else{
  System.out.print("\r>");
}

答案 2 :(得分:3)

a=1;
b=2;

x=3;
y=4;

answer = a > b ? x : y;

answer=4因为条件为假,所以需要y值。

问号(?)
。条件为真时使用的值

冒号(:)
。条件为假时使用的值

答案 3 :(得分:2)

也许它可以成为Android的完美范例, 例如:

void setWaitScreen(boolean set) {
    findViewById(R.id.screen_main).setVisibility(
            set ? View.GONE : View.VISIBLE);
    findViewById(R.id.screen_wait).setVisibility(
            set ? View.VISIBLE : View.GONE);
}

答案 4 :(得分:1)

它是一个三元运算符,用简单的英语表示"if row%2 is equal to 1 then return < else return /r"

答案 5 :(得分:1)

同样,虽然我会将答案发给我的另一个相关问题,

a = x ? : y;

相当于:

a = x ? x : y;

如果x为false或null,则取y的值。

答案 6 :(得分:0)

它们被称为三元运算符,因为它们是Java中唯一的运算符。

if ... else结构的不同之处在于,它们会返回一些东西,而这些东西可以是任何东西:

  int k = a > b ? 7 : 8; 
  String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();