public class Test {
public static int y;
public static int foo(int x) {
System.out.print("foo ");
return y = x;
}

public static void bar(int z) {
System.out.print("bar ");
y = z;
}

public static void main(String[] args) {
int t = 2;
assert t < 4 : bar(7);
assert t > 1 : foo(8);
System.out.print("done ");
}
}这是代码,编译是错误的。问题如题,感谢。。

解决方案 »

  1.   

    断言可以有两种形式 
    1.assert Expression1 
    2.assert Expression1:Expression2 
    其中Expression1应该总是一个布尔值,Expression2是断言失败时输出的失败消息的字符串。如果Expression1为假,则抛出一个 AssertionError,这是一个错误,而不是一个异常,也就是说是一个不可控制异常(unchecked Exception),AssertionError由于是错误,所以可以不捕获,但不推荐这样做,因为那样会使你的系统进入不稳定状态
      

  2.   

    语言规范上这样说:
    AssertStatement:
    assert Expression1 ;
    assert Expression1 : Expression2 ;
    It is a compile-time error if Expression1 does not have type boolean or Boolean.
    In the second form of the assert statement, it is a compile-time error if
    Expression2 is void (§15.1).
    所以可以认为这是规定的.
      

  3.   

    bar(7)必须是个可以打印出来的值啊~~~你不写返回值怎么能行?foo(8)写了返回值就可以通过编译~~仔细研究下assert语法吧~~~