Java 或/和邏輯

Rashmi Patidar 2023年10月12日
Java 或/和邏輯

在 Java 語言中,and (&&)/ or(||) 被歸類為邏輯運算子。運算子用於評估兩個或多個條件,並以 Boolean 格式返回輸出。and(&&) 運算子根據第一個條件評估兩個條件。當且僅當第一個條件為真時,才檢查第二個條件。因此,& 運算子僅在第一個條件返回真值時才返回真值,否則它總是返回一個 false 值。另一方面,如果兩個條件都返回 false,則 or(||) 運算子返回 false,否則它總是評估為 true。

下面是示例程式碼塊,用於說明邏輯運算子的工作。

import java.util.Scanner;

public class LogicalOperators {
  public static void main(String[] args) {
    System.out.println("Enter a string : ");
    Scanner s = new Scanner(System.in);
    String input = s.nextLine();
    if (input == null || input.isEmpty()) {
      System.out.println("Input String is null or empty");
    }
    if (input != null && !input.isEmpty()) {
      System.out.println("Input String is: " + input);
    }
  }
}

在上面的程式碼塊中,首先例項化了一個 Scanner 類。建構函式採用 InputStream 的例項並在內部將位元組轉換為字元。Scanner 物件的用途是通過控制檯從使用者那裡獲取輸入。nextLine() 方法接受字串,直到出現換行符。使用者輸入被儲存在一個變數中,即 input 變數。

現在檢查輸入變數是否為空或輸入變數為空。如果任何條件為真,則條件結果為 true

該條件用於檢查變數是否不為空且不為空。如果結果為真,則輸入字串將列印在控制檯輸出中。

請參閱上述程式的輸出。

Enter a string : 

Input String is null or empty

首先,擊中的是回車而不是明確定義的字串。在第二種情況下,輸入一個明確定義的字串,並在新行中列印。

Enter a string : 
Hi
Input String is: Hi
作者: Rashmi Patidar
Rashmi Patidar avatar Rashmi Patidar avatar

Rashmi is a professional Software Developer with hands on over varied tech stack. She has been working on Java, Springboot, Microservices, Typescript, MySQL, Graphql and more. She loves to spread knowledge via her writings. She is keen taking up new things and adopt in her career.

LinkedIn

相關文章 - Java Logic