當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Boolean logicalOr()用法及代碼示例


Java Boolean 類的 logicalOr() 方法返回對指定的布爾操作數執行邏輯或運算的結果。

用法:

public static boolean logicalOr(boolean a, boolean b)

參數:

a- 這是第一個布爾操作數

b- 這是第二個布爾操作數

返回值:

logicalOr() 方法返回對布爾參數 a 和 b 應用邏輯或運算的結果。

例子1

public class BooleanLogicalOrExample1 {
    public static void main(String[] args) {
        Boolean b1 = true;
        Boolean b2 = false;
    // if either of the bool value is true logicalOr() method will return true.
        boolean b3 = Boolean.logicalOr(b1,b2);
        System.out.println("1. logicalOr() method for "+b1+" "+b2+" is "+b3);
        boolean b4 = false;
        boolean b5 = false;
    // if both the bool value are true logicalOr() method will return false
        boolean b6 = Boolean.logicalOr(b4,b5);
        System.out.println("2. logicalOr() method for "+b4+" "+b5+" is "+b6);

    }
}

輸出:

1. logicalOr() method for true false is true
2. logicalOr() method for false false is false

例子2

import java.util.Scanner;

public class BooleanLogicalOrExample2 {
    public static void main(String[] args) {
        Boolean bool1 = true;
        Boolean bool2 = false;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number whose table you want to print:");
        int n =scanner.nextInt();
        if(n<0||n>20){
            bool1 = false;
            System.out.println("Please enter a valid number between 0-20.");
        }
        Boolean bool3 =Boolean.logicalOr(bool1,bool2);
        if(bool3==true) {
            System.out.println("Table of "+n+":");
            for (int i = 1; i < 11; i++) {
                System.out.println(n +" * "+  i + " = " + n * i);
            }
        }

    }
}

輸出:

Enter the number whose table you want to print:119
Please enter a valid number between 0-20.

例子3

import java.util.Scanner;

public class BooleanLogicalOrExample3 {
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        System.out.println("Q How many hours are there in a day?");
        System.out.print("Ans:"); int a = scanner.nextInt();
        Boolean b1 = false;
        Boolean b2 = false;
        if(a==24){
            b1 = true;
        }
        Boolean bool = Boolean.logicalOr(b1,b2);
        if(bool == true){
            System.out.println("Answer is right.");
        }
        else{
            // logicalOr() method returns false
            System.out.println("Answer is wrong.");
        }
    }
}

輸出:

Q How many hours are there in a day?
Ans:67
Answer is wrong.





相關用法


注:本文由純淨天空篩選整理自 Java Boolean logicalOr() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。