三元运算符“ ?: ”的应用

三元运算符的基本输出格式就是:变量=逻辑表达式?返回值1(true):返回值2(false)

用个简单的代码来看一下:

package hello;

public class gaofushuai {
    public static void main(String[] args){
        int a=1;
        int b=1;
        int c=1;
        String str=a>0?"高":"矮";
        String www=b>0?"富":"穷";
        String sss=c>0?"帅":"丑";
        System.out.print(str+www+sss);
    }

}

输出结果的过程:

通过问号前面的三个逻辑表达式

a>0      b>0     c>0

如果逻辑是对的,则返回值为:

str=“高”,www=“富”,sss=“帅”

如果逻辑是错的,则输出结果为:

str=“矮”,www=“穷”,sss=“丑”

原文地址:https://www.cnblogs.com/doubiqi/p/5013825.html