有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么三元表达式在if语句正常工作时不更新值?

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

是否平衡=(数学abs(左-右)<=1) ? 真:假

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

共 (2) 个答案

  1. # 1 楼答案

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

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

  2. # 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