[SWEA] 두문자어

문제 보러가기

제한사항

각 테스트 케이스의 첫 번째 줄에는 영어 소문자로 이루어진 세 문자열이 주어진다.

각 문자열의 길이는 1이상 20이하이다.

첫번째 생각

split(“ “)으로 나눈 뒤, 첫번째 문자만 저장하고, toUpperCase() 하면 쉽게 풀릴 것이라 생각했다.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- 틀린 코드입니다 -->
import java.util.Scanner;

public class Solution {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		for(int tc=1;tc<=T;tc++) {
			String s = sc.nextLine();
			String[] arr = s.split(" ");
			StringBuilder sb = new StringBuilder();
			for(int i=0; i<arr.length; i++) {
				sb.append(arr[i].charAt(0));
			}
			System.out.println("#"+tc+" "+sb.toString().toUpperCase());
		}
	}
}

nextLine()을 사용하면서, 전에도 nextLine()때문에 제대로 안돌아갔던게 생각났고

역시나 오류가 났다.

두번째 생각

다시 한번 생각해보았다.

nextInt() 뒤에 nextLine()을 쓸 때 오류가 났었고,

그 이유는 nextInt() 는 사용자의 개행문자(new Line, 엔터키)를 제거하지 않기 때문

nextLine()이 이 개행문자를 물고 들어가서 생기는 오류이다.

이것의 해결방법은 두가지이다.

  1. nextInt() 뒤에 nextLine()을 한 번 넣어줘서 개행문자를 처리한다.
  2. nextInt로 받지말고 nextLine으로 바꾸고 캐스팅을 한다.

나는 1번 방법을 택해서 문제를 해결하였다.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Scanner;

public class Solution {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		sc.nextLine();
		for(int tc=1;tc<=T;tc++) {
			String s = sc.nextLine();
			String[] arr = s.split(" ");
			StringBuilder sb = new StringBuilder();
			for(int i=0; i<arr.length; i++) {
				sb.append(arr[i].charAt(0));
			}
			System.out.println("#"+tc+" "+sb.toString().toUpperCase());
		}
	}
}