サムネがコーヒーの記事は書きかけです。

HashMapを利用した出現回数のカウント【Java】

Pythonには辞書型があるので一瞬で終わりますが、JavaはHashMapというものを使わないといけないので、まとめておきます。

HashMapの使い方

以下のように宣言して使います。

HashMap<String, Integer> hashMap
                = new HashMap<String, Integer>();

出現数のカウント

HashMapを使用して、入力された文字の中に含まれるそれぞれの文字数をカウントします。

import java.io.*;
import java.util.*;
class CountChars {
    static void count(String inputString) {
        
        HashMap<Character, Integer> charCountMap
                = new HashMap<Character, Integer>();

        for (int i = 0; i < inputString.length(); i++) {
            if (charCountMap.get(inputString.charAt(i)) == null){
                charCountMap.put((char) inputString.charAt(i), 1);
            }else{
                int numChar = charCountMap.get(inputString.charAt(i)) ;
                charCountMap.put((char) inputString.charAt(i), numChar + 1);
            }
        }

        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()){
            System.out.println("Chr = " + entry.getKey() + ", Count = " + entry.getValue());
    }
    } 
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        while (true) {
            System.out.print("input string: ");
            String entry = in.nextLine();
            count(entry);

            System.out.print("q to quit. or any other keys");
            entry = in.nextLine();
            String[] words = entry.split(" ");
            if ("q".equals(words[0])) break;
        }
    }
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です