一段断言assert 不生效的问题

public class Test {
  public static void main(String[] args) {
    int x = 1; // 改成 x=0 也不行;
    if (x == 0) {
      System.out.println("x=0");
    } else {
      assert x == 1 : x;
      System.out.println("x=1");
    }
  }
}


其实问题很简单,他的逻辑运算有问题
1 如果是0,根本到不了那个assert 部分
2 如果是1, 则 x==1 是正确的,也不会产生异常

修改方法
public class Test {
  public static void main(String[] args) {
    int x = 1; // 改成 x=0 也不行;
    if (x == 0) {
      System.out.println("x=0");
    } else {
      assert x == 0 : x; // 这里改成 ==0 就行了
      System.out.println("x=1");
    }
  }
}



运行方法

引用:
java -ea -cp . test.Test


抛出异常为
Exception in thread "main" java.lang.AssertionError: 1
at test.Test.main(Test.java:9)
快乐渡过每一天,减肥坚持每一天