邏輯運算子

Java 中級

Jim White

Java Developer

AND、OR 與 NOT

  • 邏輯運算子可在一個敘述中結合多個條件
  • 三種常見運算子:
    • AND
    • OR
    • NOT
Java 中級

AND

  • 檢查兩個條件是否都為 true
boolean isLoggedIn = true;
boolean isAdmin = true;

// Both are true
if (isLoggedIn && isAdmin) {
  System.out.println("Welcome admin!");
} else {
  System.out.println("You shall not pass.");
}
Welcome admin!
  • 只要有一個為 false,&& 會回傳 false
boolean isLoggedIn = false;
boolean isAdmin = true;

// Only one is true, so else is executed
if (isLoggedIn && isAdmin) {
  System.out.println("Welcome admin!");
} else {
  System.out.println("You shall not pass.");
}
You shall not pass.
Java 中級

OR

  • 檢查是否任一條件為 true
boolean isAdmin = true;
boolean isModerator = false;

// Only one condition is true
if (isAdmin || isModerator) {
  System.out.println("Welcome!");
} else {
  System.out.println("You shall not pass.");
}
Welcome!
  • 只要其中一個或兩個條件為 true 就回傳 true
boolean isAdmin = true;
boolean isModerator = true;

// Both conditions are true
if (isAdmin || isModerator) {
  System.out.println("Welcome!");
} else {
  System.out.println("You shall not pass.");
}
Welcome!
Java 中級

NOT

  • true 變為 falsefalse 變為 true
boolean isLoggedIn = false;

// isLoggedIn is false, so !isLoggedIn is true
if (!isLoggedIn) {
    System.out.println("You need to log in!");
} else {
    System.out.println("You are logged in, continue!");
}
You need to log in!
Java 中級

邏輯運算子搭配 if-else if-else

int score = 90;
boolean isAttending = false;

if (score > 80 && isAttending) {
  System.out.println("Excellent work!");
} else if (score > 80 && !isAttending) {
  System.out.println("Good work, but attendance is important.");
} else if (score <= 80 && isAttending) {
  System.out.println("You need to work harder.");
} else {
  System.out.println("You need to work harder and attend classes.");
}
Good work, but attendance is important.
Java 中級

重點回顧

下表總結了運算子 &&||! 的值:

a b a && b a | | b !a
true true true true false
true false false true false
false true false true true
false false false false true
  • 邏輯運算子可用於布林值,或可求值為布林的運算式
boolean a = true && (!false || (true && false)); // a is true
boolean b = (7 <= 3) || (3 >= 5); // b is false
Java 中級

一起來練習吧!

Java 中級

Preparing Video For Download...