Logical Operators Part 3
Coddy Java 여정의 기초 섹션에 포함된 레슨. 73개 중 25번째.
여러 조건을 확인할 때, 컴퓨터는 최종 답을 아는 즉시 확인을 중단합니다(이를 단락 평가(short-circuit evaluation)라고 합니다).
예를 들어:
int x = 0;
int y = 5;
boolean result = x != 0 && y / x > 2;여기서 x는 0과 같으므로 y / x > 2를 평가하지 않습니다. 순서를 바꾸면 다음과 같습니다:
boolean result = y / x > 2 && x != 0;y가 0으로 나뉘게 되는데, 이는 수학적으로 허용되지 않으므로 오류가 발생합니다.
이 기법은 논리식의 평가를 최적화하는 데 사용됩니다. 예를 들어:
int a = 0;
int b = 2;
int c = 3;
int d = 5;
boolean result = (a > 0 && b < 2) || (c < -5 && d < 10);이 예시에서 a > 0과 c < -5가 모두 거짓이므로 b < 2와 d < 10은 평가되지 않습니다.
챌린지
초급태양광 패널 에너지 생산에 좋은 날인지 결정하는 프로그램을 만들어 봅시다.
다음 변수들을 초기화하세요:
isSunny: 값 truewindSpeed: 값 5.4temperature: 값 23solarPanelOutput: 값 9isCloudy: 값 false
이 모든 조건들을 확인하는 하나의 논리식을 작성하세요:
- 날씨가 맑음 (sunny)
- 풍속 (wind speed)이 10 미만임
- 태양광 패널 출력 (solar panel output)이 15 미만임
- 기온 (temperature)이 20 초과 또는 구름이 없음
직접 해보기
public class Main {
public static void main(String[] args) {
// 변수 초기화
// 아래의 각 플레이스홀더 값을 작업에서 요구하는 값으로 바꾸세요
boolean isSunny = false;
double windSpeed = 0.0;
int temperature = 0;
int solarPanelOutput = 0;
boolean isCloudy = false;
// 완전한 논리 표현식
// 아래의 플레이스홀더를 네 가지 조건을 모두 결합하는 하나의 표현식으로 바꾸세요
boolean result = false;
// 아래 줄들을 삭제하지 마세요
System.out.println("Checking conditions for solar energy production...");
System.out.println("1. Is it sunny? " + isSunny);
System.out.println("2. Is wind speed safe? " + (windSpeed < 10));
System.out.println("3. Can panels produce more? " + (solarPanelOutput < 15));
System.out.println("4. Is temperature good OR no clouds? " + (temperature > 20 || !isCloudy));
System.out.println("\nFinal result - Good day for solar energy production: " + result);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else직접 연습해 보세요: 온라인 Java 컴파일러