[CodeUp / 1412 / Java] 알파벳 개수 출력하기

최대 1 분 소요

문제

링크 : https://codeup.kr/problem.php?id=1412

오답풀이

import java.util.Scanner;
public class Main{
    
    public static void main(String[] args){
        int alph[] = new int[26];
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        
        int strLen = str.length();
        
        for(int i=0;i<strLen;i++){
            char ch = str.charAt(i);
            alph[ch - 'a']++;    
        }
        
        for(int i=0;i<strLen;i++){
            char ch = 'a' + i; // 컴파일에러
            /*
            Main.java:17: error: incompatible types: possible lossy conversion from int to char
            char ch = 'a' + i;
                          ^
            1 error
            */
            int cnt = alph[i];
            System.out.println(ch + ":" + cnt);    
        }
    }
    
}

정답풀이

import java.util.Scanner;
public class Main{
    
    public static void main(String[] args){
        int alph[] = new int[26];
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        
        int strLen = str.length();
        
        for(int i=0;i<strLen;i++){
            char ch = str.charAt(i);
            int idx = ch - 'a';
            
            if(ch >= 'a' && ch <= 'z' ) alph[idx]++;    
        }
        
        for(int i=0;i<26;i++){
            char ch = (char) ('a' + i ); // (char)로 형변환 안하면 컴파일에러
            
            int cnt = alph[i];
            System.out.println(ch + ":" + cnt);    
        }     
    }
}

오답 Point