什么是问号“?”和冒号“:”运营商用于? [英] What is a Question Mark "?" and Colon ":" Operator Used for?

查看:140
本文介绍了什么是问号“?”和冒号“:”运营商用于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.

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();
}


推荐答案

这是三元条件运算符,可以在任何地方使用,而不仅仅是print语句。它有时被称为三元运算符,但它不是唯一的三元运算符,只是最常见的一个。

This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.

以下是维基百科展示其工作原理的一个很好的例子:

Here's a good example from Wikipedia demonstrating how it works:


用C,Java和JavaScript编写一个传统的if-else结构:

A traditional if-else construct in C, Java and JavaScript is written:

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

这可以改写为以下语句:

This can be rewritten as the following statement:

result = a > b ? x : y;


基本上采用以下形式:

boolean statement ? true result : false result;

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

So if the boolean statement is true, you get the first part, and if it's false you get the second one.

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

Try these if that still doesn't make sense:

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

这篇关于什么是问号“?”和冒号“:”运营商用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆