Java 程序检查三个布尔变量中的两个是否为真
javaobject oriented programmingprogramming更新于 2024/4/13 19:24:17
在本文中,我们将了解如何检查三个布尔变量中的两个是否为真。布尔变量是只能包含真或假值的数据类型。
下面是相同的演示 −
输入
假设我们的输入是 −
输入:true、true、false
输出
所需的输出将是 −
结果:三个变量中有两个为真
算法
步骤 1 - 开始 步骤 2 - 声明 4 个布尔值,即 my_input_1、my_input_2、my_input_3 和 my_result 步骤 3 - 从用户那里读取所需值/定义值 步骤 4 - 使用 if-else 条件,比较三个中的两个每次使用 AND 运算符计算值。 步骤 5 - 显示结果 步骤 6 - 停止
示例 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
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

