이 글에서는 3개의 부울(Boolean) 변수 중 정확히 2개가 true인지 확인하는 방법을 알아봅니다. 부울 변수는 true 또는 false 값만 가질 수 있는 데이터 타입으로, 조건 판단 로직에서 매우 자주 사용됩니다.
아래는 이번 예제의 입출력 결과입니다.
입력 및 출력 예시
입력
Input : true, true, false
출력
Result : Two of the three variables are true
알고리즘
이 문제를 해결하기 위한 절차는 다음과 같습니다.
Step 1 - 시작(START) Step 2 - 부울 변수 4개를 선언합니다: my_input_1, my_input_2, my_input_3, my_result Step 3 - 사용자로부터 값을 입력받거나 값을 직접 정의합니다 Step 4 - if-else 조건문과 AND(&&), OR(||) 연산자를 사용하여 세 값 중 두 개씩 비교합니다 Step 5 - 결과를 화면에 출력합니다 Step 6 - 종료(STOP)
예제 1: 사용자 입력을 받는 경우
다음 예제에서는 Scanner 객체를 사용해 사용자로부터 부울 값을 직접 입력받아 처리합니다.
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
핵심 로직 설명
이 프로그램의 핵심은 다음 조건문입니다.
- 첫 번째 변수(
my_input_1)가true라면, 나머지 두 변수 중 하나만true여도 조건이 충족되므로 OR(||) 연산을 사용합니다. - 첫 번째 변수가
false라면, 나머지 두 변수가 모두true여야 하므로 AND(&&) 연산을 사용합니다.
이렇게 하면 복잡한 조건 조합 없이도 간결하게 "3개 중 2개가 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
마무리
이처럼 if-else 조건문과 논리 연산자를 조합하면 3개의 부울 변수 중 2개가 true인지 손쉽게 확인할 수 있습니다. 참고로, 더 일반적인 방법으로는 세 변수의 합을 세어 정확히 2인지 검사하거나, XOR 개념을 활용하는 방식도 있습니다. 상황에 맞는 방식을 선택하여 활용해 보시기 바랍니다.