【问题标题】:Why can't I replace if statement with conditional operator (?:)?为什么我不能用条件运算符 (?:) 替换 if 语句?
【发布时间】:2015-07-20 14:52:29
【问题描述】:

我一直在努力转身

private PlaneClass preferredClass;

if (preferredClass == PlaneClass.FIRST_CLASS)
    preferredClass = PlaneClass.ECONOMY_CLASS;
else
    preferredClass = PlaneClass.FIRST_CLASS;

进入

preferredClass == PlaneClass.FIRST_CLASS ? 
                preferredClass = PlaneClass.ECONOMY_CLASS 
                               : preferredClass = PlaneClass.FIRST_CLASS;

if 语句编译。 条件运算符没有。 (错误消息:1. 类型不匹配:无法从 PlaneClass 转换为布尔值 2. 标记“=”上的语法错误。还有另外两个错误......)。我哪里做错了?

【问题讨论】:

    标签: java if-statement conditional ternary-operator


    【解决方案1】:

    语法是:

    condition ? value1 : value2;
    

    不是

    condition ? statement1 : statement2;
    

    条件运算符是表达式,而不是语句。它不像if 语句那样执行语句:它返回一个值。

    你的意思是:

    preferredClass = (preferredClass == PlaneClass.FIRST_CLASS ? 
                PlaneClass.ECONOMY_CLASS : PlaneClass.FIRST_CLASS);
    

    【讨论】:

    • 这是一个基本的区别,我不知何故忽略了。谢谢。
    【解决方案2】:

    应该是

    preferredClass == PlaneClass.FIRST_CLASS ? 
                 PlaneClass.ECONOMY_CLASS 
                               :  PlaneClass.FIRST_CLASS;
    

    【讨论】:

      【解决方案3】:
      preferredClass = preferredClass == PlaneClass.FIRST_CLASS ? PlaneClass.ECONOMY_CLASS : PlaneClass.FIRST_CLASS;
      

      会成功的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-20
        • 2012-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-13
        • 2011-02-18
        • 2010-12-03
        相关资源
        最近更新 更多