[문제]
첫 줄에 필요한 기능의 수 N, 두 번째 줄에 시간 T와 M, 이후 N만큼 시간(분) c가 주어진다. 시작 시간 T시 M분 부터 작업을 시작했을 때 N만큼 주어지는 시간 c의 총합을 더하면 어떤 시간이 될지 프로젝트 관리를 하는 문제이다.
[코드]
package week1;
import java.util.Scanner;
public class ProjectManaging {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int T = scanner.nextInt();
int M = scanner.nextInt();
for (int i = 0; i < N; i++) {
M += scanner.nextInt();
}
T += M / 60;
M %= 60;
T %= 24;
System.out.println(T + " " + M);
}
}
[풀이]
- java.util.Scanner의 Scanner를 사용하여 정수들을 받는다. 모두 계산에 사용되므로 정수로 받아야 한다.
- N만큼 받는 수를 한 번씩 T:M에 더해 계산할 필요가 없고, 모두 더한 뒤 이를 60으로 나눈 몫을 시간 T에 더하고, 나머지를 작업 후 최종 M으로 둔다.
- 이전에 60으로 나눈 몫을 T에 더하고, 24로 나눈 나머지를 최종 T로 둔다. 24로 나눈 몫은 일수로 따로 세지 않기 때문에 버려도 된다. 이를 출력하면 된다.
[해설 풀이]
Scanner scan = new Scanner(System.in);
// int N = Integer.parseInt(scan.nextLine());
int N = scan.nextInt();
scan.nextLine();
String[] input = scan.nextLine().split(" ");
int T = Integer.parseInt(input[0]);
int M = Integer.parseInt(input[1]);
해설에선 위처럼 접근하고 있는데 이유는 T와 M이 공백과 함께 나오고 있기 때문이다. Scanner::nextInt()는 공백과 개행을 건너뛰어 정수를 가져오기 때문에 굳이 이렇게 할 필요는 없지만 한 번 구현해보았다. 그런데 nextInt()와 nextLine()을 섞어 사용하면 Integer.parseInt()에서 예외가 발생하였다.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at week1.day2.day2refactor.main(day2refactor.java:12)
Process finished with exit code 1
이는 Scanner::nextInt()가 정수만 가져간 뒤 입력과 함께 들어온 개행을 가져가지 않았기 때문에 발생하는 문제이다. 때문에 Scanner::nextLine()과 nextInt()를 같이 쓸 때는 nextInt() 후 nextLine()을 꼭 사용해줘야 한다.
'알고리즘' 카테고리의 다른 글
[구름톤 챌린지, JAVA] 1주차 합 계산기 (1) | 2024.02.07 |
---|---|
[구름톤 챌린지, JAVA] 1주차 운동 중독 플레이어 (0) | 2024.02.02 |