Algorithm
-
Read three boolean variables:
boolVar1
,boolVar2
, andboolVar3
. -
Initialize a counter variable
trueCount
to 0. -
Check if
boolVar1
is true:- If true, increment
trueCount
by 1.
- If true, increment
-
Check if
boolVar2
is true:- If true, increment
trueCount
by 1.
- If true, increment
-
Check if
boolVar3
is true:- If true, increment
trueCount
by 1.
- If true, increment
-
Check if
trueCount
is greater than or equal to 2:- If true, print "At least two out of three variables are true."
- If false, print "Less than two variables are true."
Code Examples
#1 Code Example- Check if two of the three boolean variables are true
Code -
Java Programming
// Java Program to check if 2 variables
// among the 3 variables are true
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// create 3 boolean variables
boolean first;
boolean second;
boolean third;
boolean result;
// get boolean input from the user
Scanner input = new Scanner(System.in);
System.out.print("Enter first boolean value: ");
first = input.nextBoolean();
System.out.print("Enter second boolean value: ");
second = input.nextBoolean();
System.out.print("Enter third boolean value: ");
third = input.nextBoolean();
// check if two are true
if(first) {
// if first is true
// and one of the second and third is true
// result will be true
result = second || third;
}
else {
// if first is false
// both the second and third should be true
// so result will be true
result = second && third;
}
if(result) {
System.out.println("Two boolean variables are true.");
}
else {
System.out.println("Two boolean variables are not true.");
}
input.close();
}
}
Copy The Code &
Try With Live Editor
Output
Enter first boolean value: true
Enter second boolean value: false
Enter third boolean value: true
Two boolean variables are true.
Enter second boolean value: false
Enter third boolean value: true
Two boolean variables are true.
Demonstration
Java Programing Example to Check if two of three boolean variables are true-DevsEnv