Java 程式 - 檢查三個布林變數中是否兩個為 true
在本文中,我們將瞭解如何檢查三個布林變數中是否有兩個為 true。布林變數是可以僅包含 true 或 false 值的資料型別。
以下是示例演示 −
輸入
假設我們的輸入是 −
Input : true, true, false
輸出
所需的輸出為 −
Result : Two of the three variables are true
演算法
Step 1 - START Step 2 - Declare 4 boolean values namely my_input_1, my_input_2, my_input_3 and my_result Step 3 - Read the required values from the user/ define the values Step 4 - Using an if-else condition, compare two of the three values each time using an AND operator. Step 5 - Display the result Step 6 – Stop
示例 1
在這裡,使用者根據提示輸入。你可以在我們的程式設計練習工具
中實際嘗試此示例。
import java.util.Scanner;
public class BooleanValues {
public static void main(String[] args) {
boolean my_input_1, my_input_2, my_input_3, my_result;
System.out.println("The required packages have been imported");
System.out.println("A scanner object has been defined ");
Scanner my_scanner = new Scanner(System.in);
System.out.print("Enter the first boolean value: ");
my_input_1 = my_scanner.nextBoolean();
System.out.print("Enter the second boolean value: ");
my_input_2 = my_scanner.nextBoolean();
System.out.print("Enter the third boolean value: ");
my_input_3 = my_scanner.nextBoolean();
if(my_input_1) {
my_result = my_input_2 || my_input_3;
} else {
my_result = my_input_2 && my_input_3;
}
if(my_result) {
System.out.println("Two of the three variables are true");
} else {
System.out.println("Two of the three variables are false");
}
}
}輸出
The required packages have been imported A scanner object has been defined Enter the first boolean value: true Enter the second boolean value: true Enter the third boolean value: false Two of the three variables are true
示例 2
在這裡,整數已預先定義,其值已訪問並在控制檯上顯示。
public class BooleanValues {
public static void main(String[] args) {
boolean my_input_1, my_input_2, my_input_3, my_result;
my_input_1 = true;
my_input_2 = true;
my_input_3 = false;
System.out.println("The three boolean values are defined as " +my_input_1 +" , " +my_input_2 + " and " +my_input_3);
if(my_input_1) {
my_result = my_input_2 || my_input_3;
} else {
my_result = my_input_2 && my_input_3;
}
if(my_result) {
System.out.println("Two of the three variables are true");
} else {
System.out.println("Two of the three variables are false");
}
}
}輸出
The three boolean values are defined as true , true and false Two of the three variables are true
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP