본문 바로가기

Coding Test/백준

[백준/자바] 1152 - 단어의 개수

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String sentence = br.readLine().trim();

        String[] arr = sentence.split(" ");

        int result = arr.length;
        if(sentence.equals("")) result = 0;

        System.out.println(result);

        br.close();
    }
}

  

빈 문자열을 입력받는 경우를 고려해야 한다.

  


  

❌ 틀린 답안 ❌

  

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String sentence = br.readLine();

        String[] arr = sentence.trim().split(" ");

        System.out.println(arr.length);

        br.close();
    }
}