https://www.acmicpc.net/problem/2480
Answer
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
int diceNum1 = 0;
int diceNum2 = 0;
int diceNum3 = 0;
int reward = 0;
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
diceNum1 = Integer.parseInt(st.nextToken());
diceNum2 = Integer.parseInt(st.nextToken());
diceNum3 = Integer.parseInt(st.nextToken());
} catch(IOException e) {
System.err.println("ERROR : " + e.getMessage());
}
if(diceNum1 == diceNum2 && diceNum1 == diceNum3)
reward = 10000 + diceNum1 * 1000;
else if(diceNum1 == diceNum2 || diceNum1 == diceNum3)
reward = 1000 + diceNum1 * 100;
else if(diceNum2 == diceNum3)
reward = 1000 + diceNum2 * 100;
else {
int max = Math.max(diceNum1, Math.max(diceNum2, diceNum3));
reward = max * 100;
}
System.out.println(reward);
}
}
Code Review
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
diceNum1 = Integer.parseInt(st.nextToken());
diceNum2 = Integer.parseInt(st.nextToken());
diceNum3 = Integer.parseInt(st.nextToken());
} catch(IOException e) {
System.err.println("ERROR : " + e.getMessage());
}
`try-with-resources`로 try에 자원 객체를 전달하여, try 작업이 끝나면 자동으로 자원을 반환하도록 해준다.
`System.in`으로 사용자로부터 입력받은 데이터를 바이트 스트림으로 받는다.
`InputStreamReader` 클래스로 바이트 스트림을 문자 기반 스트림으로 변환해 준다.
`BufferedReader` 클래스로 문자 스트림을 읽는다.
`StringTokenizer` 클래스로 문자열 한 행을 공백 구분자로 나눈다.
`st.nextToken()`으로 공백으로 구분된 문자를 차례로 반환한다.
if(diceNum1 == diceNum2 && diceNum1 == diceNum3)
reward = 10000 + diceNum1 * 1000;
else if(diceNum1 == diceNum2 || diceNum1 == diceNum3)
reward = 1000 + diceNum1 * 100;
else if(diceNum2 == diceNum3)
reward = 1000 + diceNum2 * 100;
else {
int max = Math.max(diceNum1, Math.max(diceNum2, diceNum3));
reward = max * 100;
}
`diceNum1 == diceNum2 && diceNum1 == diceNum3` 조건으로 같은 눈이 3개 나오는 경우를 먼저 처리한다.
위에서 3개가 같은 경우를 처리했으므로, `diceNum1 == diceNum2 || diceNum1 == diceNum3` 조건으로 같은 눈이 2개 나오는 경우를 처리한다.
위에서 같은 눈이 2개 나오는 경우 중 첫 번째 주사위 기준만 처리했으므로, `diceNum2 == diceNum3` 조건으로 두 번째 주사위 기준을 처리한다.
모두 다른 눈이 나오는 경우를 `Math.max()` 함수를 사용하여 diceNum2와 diceNum3의 최댓값을 구한 후, 그 최댓값과 diceNum1의 최댓값을 최종으로 구한다.
Result