Menu
CoddyTech

逻辑运算符第 4 部分

本课属于 Coddy Java 学习旅程的“基础知识”单元。第 26 课,共 73 课。

德摩根定律可以帮助我们简化含有 NOT 的表达式。处理逻辑表达式时,有时我们需要简化或重新排列它们。

当两个由 and 连接的条件前面有 not 时,你可以把它拆分成两个部分。and 会变成 or,每个部分前面都有自己的 not:

!(A && B) 等同于 (!A) || (!B)

例如:

// 来看看一个数是否不在 1 到 10 之间。
int number = 15;
// 这两个表达式是等价的:
boolean result1 = !(number >= 1 && number <= 10);
boolean result2 = !(number >= 1) || !(number <= 10);
System.out.println(result1);  // true
System.out.println(result2);  // true

反过来也成立:!(A || B) 和 (!A) && (!B) 相同。

例如:

// 检查一个人是否既不是学生,也没有工作
boolean isStudent = false;
boolean isEmployed = false;
// 这两个表达式是等价的:
boolean result1 = !(isStudent || isEmployed);
boolean result2 = !(isStudent) && !(isEmployed);
System.out.println(result1);  // true
System.out.println(result2);  // true
challenge icon

挑战

入门

你正在帮助一家宠物店创建一个系统,用来判断是否可以把宠物卖给顾客。

初始化以下变量:

  • hasLicense 的值为 true
  • hasSpace 的值为 false
  • hasExperience 的值为 true

编写以下逻辑表达式来判断:

  • canSellRegularPet:顾客需要有许可证或经验,并且必须有空间
  • canSellExoticPet:顾客需要同时有许可证和经验,并且必须有空间
  • cannotSellAnyPet:顾客没有许可证且没有经验,或者没有空间
  • result:canSellRegularPet 或 canSellExoticPet 或 cannotSellAnyPet

提示:编写需求所描述的条件,而不是变量当前保存的值。“必须有空间” → hasSpace;“没有空间” → !hasSpace。只有当需求与变量名表示的内容相反时才使用 !,例如“没有许可证” → !hasLicense。

亲手试试

public class Main {
    public static void main(String[] args) {
        // 初始化变量
        

        // 计算条件
        boolean canSellRegularPet = 
        boolean canSellExoticPet = 
        boolean cannotSellAnyPet =
        boolean result =

        // 不要删除下面的代码行
        System.out.println("Can sell regular pet: " + canSellRegularPet);
        System.out.println("Can sell exotic pet: " + canSellExoticPet);
        System.out.println("Cannot sell any pet: " + cannotSellAnyPet);
        System.out.println("Result: " + result);
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: Java 在线编译器