断言不起作用 [英] Assertion not working
问题描述
我正在尝试编写一个Assertion来检查用户给出的大小是否为正值,如果不是则使其为正数,此语句在类构造函数内部,它接受size值然后生成一个数组[size] 。我写了下面的代码,我认为是正确的。
I am trying to write an Assertion to check if the size the user gives is a positive value, if not then make it positive, this statement is inside the class constructor which takes the size value and then makes an array[size]. I have written the below code which i believe to be correct.
public Grid(int size) {
try{
assert size > 0 ;
}
catch(AssertionError e){
size = Math.abs(size);
}
setLayout(new GridLayout(size, size));
grid = new JButton[size][size];
}
虽然我似乎从未评估过我的断言并继续该程序然后导致NegativeArraySize错误(我试图避免)
Though I never seems to evaluate my assertion and continues the program then causes the NegativeArraySize error( which i am trying to avoid)
我也试过了
assert size>0;
并且程序无法停止负值..
And the program fails to stop for negative values..
我最近在mac上运行java时遇到了一些问题,所以我不知道我的代码是否正确,或者它是否只是其中一个奇怪的mac怪癖!并且应该只使用
I have had a few problems with running java on mac recently, so i don't know if my code is right or if it is just one of those odd mac quirks!! and should just use
size=Math.abs(size);
谢谢Sam,
推荐答案
你需要用 -ea
开关运行程序(启用断言),否则没有断言
JVM将完全运行指令。根据断言有点危险。我建议你做这样的事情:
You need to run your program with the -ea
switch (enable assertions), otherwise no assert
instructions will be run by the JVM at all. Depending on asserts is a little dangerous. I suggest you do something like this:
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];
}
第二个建议的好处是可以向您展示其他部分的潜在编程错误你的代码,而第一个默默地忽略它们。这取决于您的使用案例。
The second suggestion has the benefit of showing you potential programming errors in other parts of your code, whereas the first one silently ignores them. This depends on your use case.
这篇关于断言不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!