개발 관련/java
[백준] 9498번: 시험 성적 (java, python)
홍비
2022. 7. 12. 12:44
https://www.acmicpc.net/problem/9498
9498번: 시험 성적
시험 점수를 입력받아 90 ~ 100점은 A, 80 ~ 89점은 B, 70 ~ 79점은 C, 60 ~ 69점은 D, 나머지 점수는 F를 출력하는 프로그램을 작성하시오.
www.acmicpc.net
🗒 풀이
java
1) switch~case문 이용
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int score = sc.nextInt();
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");
break;
}
sc.close();
}
}
Scanner로 성적을 입력받아 10으로 나눈 뒤, 각 경우에 따라 성적을 출력하게 switch문을 만들었다. 이 때, 출력을 하고 나면 break문을 통해 바로 switch문을 종료해준다.
이번에는 같은 코드로 Scanner가 아닌 BufferedReader을 사용해봤다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int score = Integer.parseInt(br.readLine());
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");
break;
}
}
}
제출 결과는 다음과 같았다.
Scanner로 제출한 것이 아래의 경우(45917477)이고, BufferedReader로 제출한 것이 위의 경우(45917757)이다.
메모리 및 시간의 성능 차이가 나는 것을 확인할 수 있다.
Scanner는 편리하지만 속도가 느리다는 단점이 있다. BufferedReader를 사용하면 입력 속도가 확연히 주는 것을 확인할 수 있다.
2) if ~ else문 사용하기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int score = Integer.parseInt(br.readLine());
if (score >= 90) System.out.println("A");
else if (score >= 80) System.out.println("B");
else if (score >= 70) System.out.println("C");
else if (score >= 60) System.out.println("D");
else System.out.println("F");
}
}
BufferedReader 사용법도 익숙해질겸 BufferedReader을 사용했다.
3) 삼항연산자 사용
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int score = Integer.parseInt(br.readLine());
System.out.println((score >= 90)? "A": (score >= 80) ? "B": (score >= 70) ? "C" : (score >= 60)? "D": "F");
}
}
2번 if ~ else문을 한줄로 표현할 수도 있다.
python
python에서는 switch~case 문이 없다.
1) if ~ else 문 사용하기
score = int(input())
if score >= 90:
print('A')
elif score >= 80:
print('B')
elif score >= 70:
print('C')
elif score >= 60:
print('D')
else:
print('F')
2) 삼항연산자 사용
score = int(input())
print('A' if score >= 90 else ('B' if score >= 80 else ('C' if score >= 70 else ('D' if score >= 60 else 'F'))))