断言练习

package com.zyq;

public class AssertTest01 {
//这个成员变量的值可以变,但最终必须还是回到原值5
static int i = 5;
public static void main(String[] args) {
assert i==6;
System.out.println("如果断言正常,我就被打印");
}
}
运行结果:

  Exception in thread "main" java.lang.AssertionError
  at com.zyq.AssertTest01.main(AssertTest01.java:7)

=================================================================================================

package com.zyq;

public class AssertTest02 {
public static void main(String[] args) {
int i = 3;
switch (i) {
case 1:
System.out.println("正常");
break;
case 2:
System.out.println("正常");
break;
case 5:
System.out.println("正常");
break;
default:
assert false:"i的值无效"; //如果i的值不是你想要的,程序就警告退出
}
System.out.println("如果断言正常,我就被打印");
}
}
运行结果:

  Exception in thread "main" java.lang.AssertionError: i的值无效
  at com.zyq.AssertTest02.main(AssertTest02.java:17)

posted on 2021-04-26 15:08  ~码铃薯~  阅读(54)  评论(0编辑  收藏  举报

导航