java - boolean 值和断言

标签 java conditional-statements assertion

我有以下方法,如果第一个数字大于第二个数字,则返回 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/

相关文章:

Java JFileChooser 返回选定的目录而不是浏览它

javascript - 是否可以使用一个 if 语句的返回值作为另一个 if 语句的条件?

Java如何在不匹配条件时重复语句

algorithm - 通过移位操作替换分支语句

c# - 在 C# 中集中 Debug.Assert 和抛出异常的更好方法?

c# - 如何使用 C# 比较两个 Json 对象

java - GSON 序列化非常非常慢

java - 无法在内存中的 sqlite 数据库上创建表,没有任何错误消息

java - AP C.S. 作业中的 Java 断言

java - 编译错误 : identifier expected