Logical Operators Part 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 の両方が false だからです。
チャレンジ
初心者太陽光パネル発電に適した日かどうかを判断するプログラムを作成しましょう
これらの変数を初期化してください:
isSunnyの値を true に設定windSpeedの値を 5.4 に設定temperatureの値を 23 に設定solarPanelOutputの値を 9 に設定isCloudyの値を false に設定
これらのすべての条件をチェックする1つの論理式を作成してください:
- 晴れている
- 風速が 10 未満
- 太陽光パネルの出力が 15 未満
- 気温が 20 以上 OR 曇っていない
チートシート
Java は複数の条件をチェックする際に短絡評価を使用します - 最終結果が決定次第、評価を停止します。
&&(AND)を使用すると、最初の条件が false の場合、2 番目の条件は評価されません:
int x = 0;
int y = 5;
boolean result = x != 0 && y / x > 2; // y / x > 2 is not evaluated||(OR)を使用すると、最初の条件が true の場合、2 番目の条件は評価されません:
int a = 0;
int b = 2;
int c = 3;
int d = 5;
boolean result = (a > 0 && b < 2) || (c < -5 && d < 10);
// b < 2 and d < 10 are not evaluatedこの最適化により、不要な計算を防ぎ、ゼロ除算などの実行時エラーを回避できます。
自分で試してみよう
public class Main {
public static void main(String[] args) {
// 変数を初期化する
// 完全な論理式
boolean result =
// 以下の行を削除しないでください
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);
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
基礎のすべてのレッスン
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else