我有以下方法,如果第一个数字大于第二个数字,则返回 true:
static boolean firstGreaterSecond(int x1, int x2) {
boolean result;
if (x1 > x2) {
result = true;
} else {
result = false;
}
return result;
}
我添加了以下断言:
actual=MyClass.firstGreaterSecond(10,11);
assert false==actual;
我被告知可以用 1 个字符替换 false==。我认为他们可能指的是 ?,如 explained here ,但无论我尝试了多少,我似乎都无法获得正确的语法。你能帮忙吗?
最佳答案
首先,
static boolean firstGreaterSecond(int x1, int x2) {
boolean result;
if (x1 > x2) {
result = true;
} else {
result = false;
}
return result;
}
可以重写为:
static boolean firstGreaterSecond(int x1, int x2) {
return x1 > x2;
}
其次,您应该能够:
actual=MyClass.firstGreaterSecond(10,11);
assert !actual;
看看 assert docs
The assertion statement has two forms. The first, simpler form is:
assert Expression1 ;
where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.
boolean
表达式的否定也是一个 boolean 表达式,因此 !actual
对断言有效。
关于java - boolean 值和断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54399109/