Logical Operators Part 4
CoddyのJavaジャーニー「基礎」セクションの一部 — レッスン 26/73。
ド・モルガンの法則は、NOTを含む式を簡略化するのに役立つルールです。論理式を扱う際には、時にはそれらを簡略化したり並べ替えたりする必要があります。
2つの条件がandで結合された状態で、その前にnotがある場合、それを2つの別々の部分に分割できます。andはorになり、各部分にそれぞれ独自のnotが付きます:
!(A && B)は(!A) || (!B)と同じです
例えば:
// Let's check if a number is NOT (between 1 and 10)
int number = 15;
// These two expressions are equivalent:
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) と同じです
例:
// Checking if a person is NOT (a student or employed)
boolean isStudent = false;
boolean isEmployed = false;
// These two expressions are equivalent:
boolean result1 = !(isStudent || isEmployed);
boolean result2 = !(isStudent) && !(isEmployed);
System.out.println(result1); // true
System.out.println(result2); // trueチャレンジ
初心者ペットショップが顧客にペットを販売できるかどうかを判断するシステムを作成するのを手伝っています。
以下の変数を初期化してください:
hasLicenseを値trueでhasSpaceを値falseでhasExperienceを値trueで
以下の論理式を記述して、判定してください:
canSellRegularPet:顧客はライセンスまたは経験のいずれかが必要で、かつスペースが必要ですcanSellExoticPet:顧客はライセンスと経験の両方が必要で、かつスペースが必要ですcannotSellAnyPet:顧客にライセンスも経験もなく、またはスペースがありませんresult:canSellRegularPetまたはcanSellExoticPetまたはcannotSellAnyPet
ヒント: 式では変数の値を直接使用してください。例えば、hasSpace は false なので、「スペースが必要です」というのは hasSpace をそのまま(! なしで)使用することを意味します — 変数はすでに実際の値を持っています。! は条件が変数の持つ値の反対を要求する場合にのみ使用します、例えば「ライセンスなし」→ !hasLicense。
チートシート
ド・モルガンの法則は、NOT演算子を含む論理式を簡略化するのに役立ちます:
!(A && B) は (!A) || (!B) に等価です
!(A || B) は (!A) && (!B) に等価です
ANDを使用した例:
int number = 15;
boolean result1 = !(number >= 1 && number <= 10);
boolean result2 = !(number >= 1) || !(number <= 10);
// 両方の式は等価ですORを使用した例:
boolean isStudent = false;
boolean isEmployed = false;
boolean result1 = !(isStudent || isEmployed);
boolean result2 = !(isStudent) && !(isEmployed);
// 両方の式は等価です自分で試してみよう
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);
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
基礎のすべてのレッスン
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