2

我写了一个 if else 条件,它使用 if not(!) 来抛出错误。但是,条件并没有像我预期的那样运行,并且无论当前用户是谁,都会引发错误:

public void findCorrectUserRole() {
    if (Book.name.equals("Test Answers")) {
        User currentUser = User.getCurrentUser()
        if (currentUser) {
            if (!currentUser.hasUserRole("Teacher") || !currentUser.hasUserRole("System Administrator")) {
                throw new LCEX("Sorry, only a teacher or System Administrator can edit this.");
            }
        }
    }else{
        "Do Something Else"
    }
}
4

2 回答 2

4

您做出了一个无效的假设,即逻辑非运算符与逻辑运算的工作方式与代数中负号的工作方式相同。有一条称为德摩根定律的规则可以帮助您安全地转换逻辑表达式。

由于您的代码是编写的,因此用户只有一种方法可以避免出现此异常,用户必须同时具有教师和系统管理员的角色:

groovy:000> a = true; b = false; !a || !b // only one is true -> true
===> true
groovy:000> a = b = false; !a || !b  // neither is true -> true
===> true
groovy:000> a = b = true; !a || !b  // both are true -> false
===> false

如果使用德摩根定律重写,这可能会更清楚(从括号内取出否定意味着运算符必须从 更改||&&);你的代码相当于这个:

if (!(currentUser.hasUserRole("Teacher") 
&& currentUser.hasUserRole("System Administrator"))) {

“不是当前用户同时具有教师角色和系统管理员角色”

这绝对不是你想要的。你想要的是

if (!currentUser.hasUserRole("Teacher") 
&& !currentUser.hasUserRole("System Administrator")) {

“当前用户没有教师角色,也没有系统管理员角色”

等效地,您可以将其写为

if (!(currentUser.hasRole("Teacher") 
|| currentUser.hasRole("System Administrator"))) {

“不是当前用户具有教师或系统管理员的角色”

德摩根定律是:

"not (A and B)" 与 "(not A) or (not B)" 相同

“非(A 或 B)”与“(非 A)和(非 B)”相同。

于 2015-05-26T15:26:47.037 回答
0

您的 if 条件错误应该是:

if (!currentUser.hasUserRole("Teacher") && !currentUser.hasUserRole("System Administrator")) {
            throw new LCEX("Sorry, only a teacher or System Administrator can edit this.");
          }

或者

if (!(currentUser.hasUserRole("Teacher") || currentUser.hasUserRole("System Administrator"))) {
            throw new LCEX("Sorry, only a teacher or System Administrator can edit this.");
          }

现在如果 currentUser 角色是“老师”,他不是“系统管理员”,所以 if 条件为真。

于 2015-05-26T15:27:06.490 回答