Programming/JAVA(eclipse)
java 3일차 정리 _ 01. 연산자(6) 3항 연산자
by yoon9i
2024. 3. 12.
package exam05_연산자;
public class Operator06_3항연산자 {
public static void main(String[] args) {
// 6. 3항 연산자
// 문법 : (조건식)? 참문장:거짓문장;
// 조건식이 참이면 참문장을 얻고 거짓이면 거짓문장을 얻는다.
int n = 100;
// 문제1) n 값이 5보다 크면 100 을 반환하고 아니면 아니면 200 을 반환하는 코드작성
System.out.println((n > 5) ? 100 : 200);
int result = (n > 5) ? 100 : 200;
System.out.println(result);
// 문제2) n 값이 5보다 크고 200 보다 작으면 "AAA" 반환하고 아니면 "BBB" 반환하는 코드작성
System.out.println(( (n > 5) && (n < 200) ) ? "AAA" : "BBB");
String result2 = ( (n > 5) && (n < 200) ) ? "AAA" : "BBB";
System.out.println(result2);
// 3항 연산자 중첩
// 문법 : (조건식)? 참문장:거짓문장;
// 참문장 또는 거짓문장이 새로운 3항 연산자가 될수 있다.
int result3 = (100>200)? ((100>50)? 100:200) : ((100 < 150)? 300:400);
System.out.println(result3); // >>> 300
}
}