您需要使用
-ea开关运行程序(启用断言),否则
assertJVM将完全不运行任何指令。依靠断言有些危险。我建议你做这样的事情:
public Grid(int size) { size = Math.max(0, size) setLayout(new GridLayout(size, size)); grid = new JButton[size][size];}甚至像这样:
public Grid(int size) { if(size < 0) { throw new IllegalArgumentException("cannot create a grid with a negative size"); } setLayout(new GridLayout(size, size)); grid = new JButton[size][size];}第二个建议的好处是向您显示了代码其他部分中潜在的编程错误,而第一个建议则无提示地忽略了它们。这取决于您的用例。



