🔑알고리즘/baekjoon
백준 11720 : 숫자의 합 - 자바 문제 풀이
pkyung
2021. 7. 28. 01:10
반응형
11720번 문제입니다.
Ineteger.parseInt()에서 자꾸 NumberFormatException이라는 에러가 나와 try-catch 문을 사용하여 오류를 잡아주긴 했습니다. 그런데 계속 있던 에러가 sc.nextLine()에서 sc.next()로 바꾸니 없어졌습니다.
아마 try - catch문을 쓰지 않아도 가능할 것 입니다.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String s = sc.next();
int ans = 0;
try {
String[] array = s.split("");
for (int i = 0; i < num; i++) {
ans += Integer.parseInt(array[i]);
}
} catch (NumberFormatException e) {
}
System.out.print(ans);
}
}
반응형