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
            }
            else
                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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.