[Java] 조건연산자 (삼항연산자) / 예제

dancingcarrot·2023년 3월 9일

Java

목록 보기
11/11
  1. 조건 연산자(삼항 연산자)
  • 조건 연산자("? : ")의 의미
    삼항 연산자로 자바언어에서 반복적인 if ~ else 문의 구조를 간단히 표현하는데 사용한다.
  • 조건 연산자의 형식
    a ? b : c ;
    a가 참이면 b의 결과 값을 가지고 a가 거짓이면 c의 결과값을 가진다.

ex)
1. if 조건문을 사용한 경우

int max;
if( x>y)
	max=x;	//true인 경우
else
	max=y;	//flase인 경우
    

1-1. 조건 연산자를 사용한 경우

int max = (x>y) ? x: y;

예제

  1. TriOperTest01.java
public class TriOperTest01	{
	
    public static void main(String[] args)	{
    
    	int x=100, y=200;
        int max = (x>y)? x : y ;
        System.out.printf("두 정수 %d와 %d 중 최대값은= %d\n", x,y,max);
    }
}

  1. TriOperTest_02.java
import java.util.Scanner;

public class TriOperTest_02	{

	public static void main(String[] args)	{
    	Scanner sc = new Scanner(System.in);
        System.out.print("영어 점수입력:");
        int sub1=sc.nextInt();
        System.out.print("수학 점수입력:");
		int sub2=sc.nextInt();
        System.out.print("국어 점수입력:");
		int sub3=sc.nextInt();
        
        int total=sub1+sub2+sub3;
        int avg=total/3;
        String result =(avg>=70)?"합격":"불합격";
        
        System.out.printf("\n총점=%d, 평균=%d, 결과=%s\n", total, avg, result);
    }
}    
        

0개의 댓글