【问题标题】:why is my ternary boolean operator showing the opposite为什么我的三元布尔运算符显示相反
【发布时间】:2014-01-21 22:59:38
【问题描述】:

三元运算符不应该作为 arg 工作吗?真假 ???因此,如果持续时间和石油比字段变量多于规定的数量,它应该返回 true.. 但这会返回 false

public class test12 {
    int duration = 260;
    int petroleum = 300;
    boolean result;

    public void checktrain(){
        boolean result = duration>=250 && petroleum>=235? true : false;
        this.result = result;
    }

    public void run(){
        System.out.print(result);
    }

    public static void main(String args[]){
        test12 tr = new test12();
        tr.run();
    }
}

【问题讨论】:

  • 根本不需要三元运算符。你可以做boolean result = duration >= 250 && petroleum >= 235

标签: java boolean return operator-keyword ternary


【解决方案1】:

你忘了打电话给checktrain()。所以它仍然是布尔值的默认值false

尝试调用该方法。

public static void main(String args[]){
test12 tr = new test12();
tr.checktrian();
tr.run();
}

而check train方法可以简单的写成

public void checktrain(){
this.result= duration>=250 && petroleum>=235;
}

甚至你也可以通过编写来避免布尔值

  public boolean checktrain(){
    return  duration>=250 && petroleum>=235;
    }

【讨论】:

    【解决方案2】:

    结果为@​​987654321@,因为您从未调用过checktrain方法,成员变量result的默认值为false

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 2021-07-14
      • 2020-01-18
      • 2019-10-08
      • 2021-06-12
      相关资源
      最近更新 更多