JAVA

[ java ] 조건문

Adose 2024. 12. 3. 16:12

1️⃣  if문 설명

  • ( 조건문장 ) 안에 있는 문장이 참일때만 실행된다.
public static void main(String[] args) {
		
	int x= 10;
	int y=20;
	
	if(x < y) {
		System.out.println("x는 y 보다 작다");
	}
		
	}

 

 

  • ( 조건문장 ) 조건이 참이 아닐때 else 사용
	int x= 10;
	int y= 20;
	
	if(x == y) {
		System.out.println("x와 y는 같다.");
	}
	else {
		System.out.println("x와 y는 다르다.");
	}

 

 

  • 다른 조건을 추가할때 else if 사용
	int x= 10;
	int y= 20;
	
	if(x == y) {
		System.out.println("x와 y는 같다.");
	}
	else if(x<y) {
		System.out.println("x는 y보다 작다.");
	} else{
System.out.println("x와 y는 다릅니다");

//if 조건문과 else if 조건문이 다 다를때 
// else 조건문이 실행된다. 

 

 

2️⃣ Switch문(제어문)

  • 어떤 변수에 값에 따라서 문장을 실행할 수 있도록 하는 제어문
  • case 문의 값은 정수, 문자, 문자열만 허용
  • switch, case, default, break 사용
int value = 1;
		
		switch(value) {
		case 1:
			System.out.println("1");
		case 2:
			System.out.println("2");
		case 3:
			System.out.println("3");
		default :
			System.out.println("그 외 다른 숫자 ");
		}
  • value가 1이기 때문에 case1 부터 차례대로 다 수행이된다.
  • value 가 2일떄는 case 2 부터 차례대로 수행이 시작된다. case1 을 뛰어넘고 case2부터 실행

 

 

📌 break

  1. break 를 만나면 그 문장을 실행하고 빠져 나온다.
  2. 해당되는 case 만 실행하고 싶을때 사용한다.
int value = 1;
		
		switch(value) {
		case 1:
			System.out.println("1");
			break;
		case 2:
			System.out.println("2");
		case 3:
			System.out.println("3");
		default :
			System.out.println("그 외 다른 숫자 ");
		}

 

 

📌 case의 조건이 여러개 일때

int month = Calendar.getInstance().get(Calendar.MONTH) + 1;

switch(month){
        case 12: case 1: case 2:
        	season="겨울";
        case 3: case 4: case 5:
        	season="봄";
        case 6 : case 7: case 8:
        	season="여름";
        default :
        	season="가을";
        }

 

 

 

3️⃣ 다중 if-else문


  • 다중 if-else문은 if-else가 연속되는 것이다.
if(조건식){
실행문장1;
}
else if(조건식2){
실행문장2; //조건식 2가 참인 경우
}
else{
실행문장 n; // 앞의 모든 조건이 거짓인경우
}