Exercise:
Write a Java Program to check if two of three Boolean variables are true.
Click Here to View the Solution!
import java.util.Scanner;
public class BooleanChecker {
public static void main(String[] args) {
boolean first;
boolean second;
boolean third;
boolean result;
// get boolean input from the user
Scanner input = new Scanner(System.in);
System.out.println("Enter Boolean values as true/false for following. ");
System.out.print("First: ");
first = input.nextBoolean();
System.out.print("Second: ");
second = input.nextBoolean();
System.out.print("Third ");
third = input.nextBoolean();
if(first) {
// if first is true
//check using OR gate ||
// if one of the second and third is true
result = second || third;
}
else {
// if first is false
// both the second and third should be true
// check using AND Gate &&
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();
}
}
Click Here to View the Output!
Enter Boolean values as true/false for following. First: true Second: false Third true Two boolean variables are true.
Click Here to View the Explanation!
- This program verifies whether the values of two out of three given
Boolean
variables tend to be equal to true or not. - This example involves user input; therefore we employ
Scanner
utility provided by Java. - In the main method, initially four
Boolean
type variables are declared. - The first three variables are reserved for storing user input.
- For the purpose of taking input from user, a
Scanner
object is instantiated. - Then a message is printed that indicates the user to enter the first value.
- To make sure that the entered value is of
Boolean
type;nextBoolean()
method is employed. Similar is the case with the second and third input. - In
if condition
, logicalOR operator
is employed that checks if thesecond
orthird
value is true or not keeping in mind that thefirst
value is supposed to be true. - On the other hand, if the
first
value is false; then thesecond
andthird
value must be true. Here logicalAND operator
is being employed.