I'm attempting to make a small program that when a user inputs a string, it counts all the letters.

Here's what I've got so far:

import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;

public class LetterTypeCount 
    public static void main(String[] args) {
        // create HashMap to store String keys and Integer values
        Map<String, Integer> myMap = new HashMap<>();

        createMap(myMap); // create map based on user input
        displayMap(myMap); // display map content

    // create map from user input
    private static void createMap(Map<String, Integer> map)
        Scanner scanner = new Scanner(System.in); // create scanner
        System.out.println("Enter a string:"); // prompt for user input
        String input = scanner.nextLine();

        // tokenize the input
        String[] tokens = input.split(" ");

        // processing input text
        for (String token : tokens)
            String letter = token.toLowerCase(); // get lowercase word

            // if the map contains the letter
            if (map.containsKey(letter)) // is letter in map
                int count = map.get(letter); // get current count
                map.put(letter, count + 1); // increment count
                map.put(letter, 1); // add new letter with a count of 1 to map

    // display map content
    private static void displayMap(Map<String, Integer> map)
        Set<String> keys = map.keySet(); // get keys

        // sort keys
        TreeSet<String> sortedKeys = new TreeSet<>(keys);

        System.out.printf("%nMap contains:%nKey\t\tValue%n");

        // generate output for each key in map
        for (String key : sortedKeys)
            System.out.printf("%-10s%10s%n", key, map.get(key));
        System.out.printf("%nsize: %d%nisEmpty: %b%n",
                map.size(), map.isEmpty());
} // end class LetterTypeCount

I've gotten it to count words, but I'm unsure how to make it count the actual letters of each word..
Help would be apppreciated.

1 Year
Discussion Span
Last Post by JamesCherrill

It's just like counting words, except simpler. Instead of splitting the String into words, you just take each char from the String and count those.


So for line 25, would I change that to have something to do with char?


You can use String's charAt method to get individual chars. Wrap that in a simple loop to get all the chars one at a time.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.