본문 바로가기

백엔드개발자 준비하기

[백엔드개발자 준비하기] 조건문

[조건문]
-if, else if, else, switch-case
-if : 가정적 조건을 나타냄(만약 ~라면)
-else : 이미 언급된 것에 덧붙여 또 다른
-switch-case : 해당 조건에 맞는 case를 찾는 문법
-스위치 문에서 어떤것을 선택하면 그곳이 시작점이고 브레이크가 없으면 스위치문을 탈출할때까지 명령을 실행한다
-break : switch 문을 실행 중 해당 조건에서 브레이크 걸리면 이후의 명령을 실행하지 않고 제어문을 탈출함

 

[조건문 예시1]

Scanner scanner = new Scanner(System.in);
		
int a = 0;
int b = 0;
int c = 0;

int max = 0;
int min = 0;
		
System.out.print("정수 3개 입력 : ");
a = scanner.nextInt();
b = scanner.nextInt();
c = scanner.nextInt();
		
System.out.println("최대값 : " + max);
System.out.println("최소값 : " + min);
		
max = a;
min = a;
		
if (b > max) 
	max = b;
if (c > max) 
	max = c;
	
if (b < min)
	min = b;
if (c < min)
	min = c;

 

[조건문 예시2]

Scanner scanner = new Scanner(System.in);
		
int a = 0;
int b = 0;
int c = 0;
		
int max = 0;
int min = 0;

System.out.print("정수 3개 입력 : ");
a = scanner.nextInt();
b = scanner.nextInt();
c = scanner.nextInt();
		
System.out.println("최대값 : " + max);
System.out.println("최소값 : " + min);
		
max = a;
min = a;
		
if (b > max) 
	max = b;
if (c > max) 
	max = c;
		
if (b < min)
	min = b;
if (c < min)
	min = c;

 

[조건문 예시3]

Scanner scanner = new Scanner(System.in);
		
int score = 0;
String grade = null;
		
System.out.print("점수 입력 : ");
score = scanner.nextInt();
		
if (score < 0 || score > 100) {
	grade = null;
} else if(score > 89) {
	grade = "A";
} else if(score > 79) {
	grade = "B";
} else if(score > 69) {
	grade = "D";
} else if(score > 59) {
	grade = "D";
} else {
	grade = "F";
}

if ((score > 59 && score < 101) && (score % 10) > 4 || score == 100) {
	grade += "+";
}

if (grade == null) {
	System.out.println("어우 배고파");
} else {
	System.out.println("점수(" + score + ") : " + grade + "학점");
}

 

[스위치문 예시1]

Scanner scanner = new Scanner(System.in);
		
int score = 0;
		
System.out.print("점수 입력 : ");
score = scanner.nextInt();
		
if (score < 0 || score > 100){
	score = 0;
}
		
switch (score / 10) {
	case 10 :
	case 9 :
		System.out.println("A학점");
		break;
	case 8 :
		System.out.println("B학점");
		break;
	case 7 :
		System.out.println("C학점");
		break;
	case 6 :
		System.out.println("D학점");
		break;
	default : 
		System.out.println("F학점");
}

 

[스위치문 예시2]

String select = "C선택";
		
switch (select) {
	case "A선택" :
		System.out.println("PC(A)를 연결합니다.");
		break;
	case "B선택" :
		System.out.println("PC(B)를 연결합니다.");
		break;
	case "C선택" :
		System.out.println("PC(C)를 연결합니다.");
		break;
	case "D선택" :
		System.out.println("PC(D)를 연결합니다.");
	default : 
		System.out.println("else와 같은 역할");
}