[백준] 11720 : 숫자의 합 - JAVA

Benjamin·2022년 11월 6일
0

BAEKJOON

목록 보기
8/70

슈도코드

solution() {
  int형 변수 answer 선언
  int형 변수 sum 선언
  for(sNumber 길이만큼 반복) {
      count 변수에서 char로 하나씩 빼내어 숫자형으로 변환하는 동시에 sum에 더하기
  }
  anwer에 sum 대입
  answer 반환
}
main () {
	N값 입력받아 int형 변수count에 저장
	길이가 N인 숫자를 입력받아 String형 변수sNumber에 저장
	solution()으로 넘기기
	sum 출력하기
}

Troubleshooting 1

import java.util.Scanner;

public class sumOfNumber01 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int count = scanner.nextInt();
		String sNumber = scanner.nextLine();
		scanner.close();
		
		solution(count, sNumber);
	}
}

문제

실행시 첫번째 라인에서 count를 입력받고 두번째 줄에서 sNumber을 입력받아야하는데,
첫번째 입력을 넣고 엔터를 치면 프로그램이 종료되는 문제가 발생!

원인

원인을 분석하여 따로 글로 정리했다.
https://velog.io/@chosj1526/Java-nextInt-사용시-주의점-nextLine-스킵현상

해결

nextLine() -> next()로 수정

Troubleshooting 2

public static int solution(int count, String sNumber) {
		int answer = 0;
		int sum = 0;
		
		for(int index = 0; index < sNumber.length(); index ++) {
			sum += Integer.parseInt(sNumber.charAt(index));
		}
		
		return answer;
	}

문제

처음에는 위와같이 for문속에서 바로 sum에 더했는데, Integer.parseInt(sNumber.charAt(index));부분에서 오류가 났다.

원인

Integer.parseInt()는 String type이 파라미터로 가능하다.
내가 한 것은 String에서 하나씩 추출하여 char로 빼냈으니 안되는것이었다.

해결

'char -> int' 형변환에 내가 약하다고 느꼈다.
아스키코드에서 0부터 9까지중에서 동일한 문자와 숫자의 값 차이는 48이니, sum += (sNumber.charAt(index) - 48);로 수정하면 어떻게 될까?
(문자 '1'을 숫자1로 변환하려면 '1'-48 을 하면됨)

제출 코드

import java.util.Scanner;

public class Main {
	
	public static int solution(int count, String sNumber) {
		int answer = 0;
		int sum = 0;
		
		for(int index = 0; index < sNumber.length(); index ++) {
			sum += (sNumber.charAt(index) - 48);
		}
		
		answer = sum;
		return answer;
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int count = scanner.nextInt();
		String sNumber = scanner.next();		
		System.out.println(solution(count, sNumber));
		scanner.close();
	}
}

공부한 지식

  • 문자열의 길이 = .length()
  • charAt() : 문자열의 인덱스에 해당하는 문자 추출 (0부터 시작)
  • 아스키코드 값 살펴봄 (숫자 0~9까지의 값)
  • nextInt() 후 nextLine() 사용에서의 오류

0개의 댓글