【问题标题】:Why ternary expression is not updating the value while if statement is working fine?为什么三元表达式在 if 语句工作正常时不更新值?
【发布时间】:2021-04-06 17:12:52
【问题描述】:

我也尝试过更改三元表达式以产生等效结果:

is_balanced = (Math.abs(lh-rh)

static boolean is_balanced=true;

public static int balHeight(Node node) {
   if(node==null) return 0;
   
   int lh  = balHeight(node.left);
   int rh  = balHeight(node.right);
   
  if(Math.abs(lh-rh)>1) is_balanced = false;
    **// ternary not working here
    // is_balanced = Math.abs(lh-rh) > 1 ? false:true;**
   
   return Math.max(lh,rh)+1;
}

【问题讨论】:

  • 这个表达式不需要三元运算符 Math.abs(lh-rh) > 1 ? false:true 只需使用 is_balanced = ! Math.abs(lh-rh) > 1

标签: java conditional-operator static-variables


【解决方案1】:

等效代码是is_balanced = Math.abs(lh - rh) > 1 ? false : is_balanced

(或者,没有三元:is_balanced = is_balanced && Math.abs(lh - rh) <= 1。)

【讨论】:

    【解决方案2】:

    这里是带三元和不带三元的示例代码,两者都产生相同的结果。这意味着按预期进行三元工作。

    public class Test {
    
      public static void main(String[] args) {
        int lh = 5;
        int rh = 10;
        boolean balanced;
        balanced = Math.abs(lh - rh) > 1;
        System.out.println("General Assignment - " + balanced);
        balanced = Math.abs(lh - rh) > 1 ? true : false;
        System.out.println("Ternary Assignment - " + balanced);
      }
    }
    

    输出 -

    General Assignment - true
    Ternary Assignment - true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多