In this article, we will understand how to check if two of three Boolean variables are true. Boolean variables are datatypes that can contain only true or false values.
Below is a demonstration of the same −
Input
Suppose our input is −
Input : true, true, false
Output
The desired output would be −
Result : Two of the three variables are true
Algorithm
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
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool
.
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");
}
}
}Output
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
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
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");
}
}
}Output
The three boolean values are defined as true , true and false Two of the three variables are true