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