逻辑运算符第 3 部分
本课属于 Coddy Java 学习旅程的“基础知识”单元。第 25 课,共 73 课。
检查多个条件时,计算机一旦知道最终答案,就会停止检查(这称为短路求值)。
例如:
int x = 0;
int y = 5;
boolean result = x != 0 && y / x > 2;这里 x 等于 0,因此不会计算 y / x > 2。如果我们反过来排列顺序:
boolean result = y / x > 2 && x != 0;这会导致错误,因为 y 将被 0 除,这在数学中是不允许的。
这种技巧用于优化逻辑表达式的求值。例如:
int a = 0;
int b = 2;
int c = 3;
int d = 5;
boolean result = (a > 0 && b < 2) || (c < -5 && d < 10);在这个示例中,b < 2 和 d < 10 不会被求值,因为 a > 0 和 c < -5 都为假。
挑战
入门我们来创建一个程序,判断今天是否适合利用太阳能板发电。
初始化以下变量:
isSunny的值为 truewindSpeed的值为 5.4temperature的值为 23solarPanelOutput的值为 9isCloudy的值为 false
创建一个逻辑表达式,检查以下所有条件:
- 天气晴朗
- 风速小于 10
- 太阳能板的输出小于 15
- 气温高于 20或没有云
亲手试试
public class Main {
public static void main(String[] args) {
// 初始化变量
// 把下面的每个占位值替换为题目要求的值
boolean isSunny = false;
double windSpeed = 0.0;
int temperature = 0;
int solarPanelOutput = 0;
boolean isCloudy = false;
// 完整的逻辑表达式
// 用一个结合全部四个条件的表达式替换下面的占位值
boolean result = false;
// 不要删除下面的代码行
System.out.println("Checking conditions for solar energy production...");
System.out.println("1. Is it sunny? " + isSunny);
System.out.println("2. Is wind speed safe? " + (windSpeed < 10));
System.out.println("3. Can panels produce more? " + (solarPanelOutput < 15));
System.out.println("4. Is temperature good OR no clouds? " + (temperature > 20 || !isCloudy));
System.out.println("\nFinal result - Good day for solar energy production: " + result);
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Java 在线编译器