복습(if문, switch문)

제이·2023년 3월 12일
post-thumbnail

if문

  • if문 형태
    : if(조건=불리언 형태){ }
    : if(a) { } b
    true일 경우 : a수행 후 b로 간다. (조건이 참 일 때만 a를 거친다)
    False일 경우 : b로 바로 간다

한 줄 문장는 { }안쳐도 되긴 하지만 오류를 빨리 찾기 위해 { }치는 것이 좋다.


switch문

  • switch문
    : 정수의 형태 (byte, int, short는 된다. long은 안된다.)
    : String은 1.7버전부터 가능. 대부분 int랑 char가 차지한다.
  • switch문의 형태
switch(n){
	case 1 :   	
	a;
	case2:     	
	b;		
}
c;

n=1일 경우 a->b->c 수행된다. 다 수행된다.
n=2일 경우 b->c 수행된다.
n=3일 경우 (1과 2가 아닐경우) 그냥 c만 수행된다.

switch(n){
	case 1 : 
    A;
	break;
    //
	case2:     	
	B;		
	break;
    //
	default:
	C;
}D;

break구문 의미 : 감싸고 있는 중괄호를 탈출하라.
break를 넣으면 n=1일 경우 case=1에서 A만 적용된다.
default문은 1, 2가 아닐 때 무조건 수행되는 조건이다.
n=1일 경우 A->D가 수행
n=2일 경우 B->D가 수행
n=1,2제외 C->D 수행

System.out.print("수를 입력하세요: ");
		int num = scan.nextInt();
//
		switch(num) {
			case 1 :
				System.out.println("A");
				break;
			case 2 :
				System.out.println("B");
			case 3 :
				System.out.println("C");
				break;
			default: 
				System.out.println("D");
---------------------------------------------
//위의 switch문을 if문으로 바꾸면?
System.out.print("수를 입력하세요: ");
		int num = scan.nextInt();
//
		if(num==1){
			System.out.println("A");
		}else if(num==2){
			System.out.println("B");
			System.out.println("C");
		}else if(num==3){
			System.out.println("C");
		}else{
			System.out.println("D");





복습 피피티 - 9/30, 10/5
profile
Hello :)

0개의 댓글