I have to write a program where I take user input and print out how many times each word prints out. Here is my code:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;

public class wordlist
    public static void main(String[] args)
        int i = 0;
        int USER_MAX = 50;
        String[] phrase = new String[USER_MAX];
        System.out.print("Enter a phrase seperated by spaces: ");
        Scanner input = new Scanner(System.in);
        phrase[i] = input.nextLine();
        String[] words = phrase[i].split("[^a-zA-Z0-9]+");

        int total = 0;

        for(i = 0; i < words.length; i++)
            total += words[i].split("[^a-zA-Z0-9]+").length;




What my code does is just count how many words the user enters, what i need is if the user types: shells shells shells cove grass shells, it should print the word and say how many times it appears so shells: 4. What I am having trouble with is how to point to each element of the array seperately.

Edited by eldiablo1121

3 Years
Discussion Span
Last Post by JamesCherrill


basically you have a list and want to transfirm it to a duplicate free list mapped to how often the item occurred in the original list.

This is a very common problem.

Here a method to solve that:

public static Map<String, Integer> listToSetWithOccurrencesCnt(String[] l) {
    HashMap<String, Integer> hm = new HashMap<String, Integer>();
    for (int i = 0; i < l.length; i++) {
        hm.put(l[i], i == 0 || !l[i].equals(l[i - 1]) ? 1 : hm.get(l[i]) + 1);
    return hm;

Hi Nikolas. Welcome to DaniWeb.

eldiablo1121 is a beginner and has been struggling withy this assignment for some time. Do you really think that dumping 8 lines of highly compacted uncommented code is going to help him?

In the worst case he will copy/paste/use that without understanding it, and thus cheat on his homework while failing to learn the skills tha the exercise was designed to give him.

It would be far better if you took some time to explain to him how to use a Map to maintain a list of unique words and their counts, and then encouraged him to research the API, perform some trial-and-error, and thus improve his Java skills to the point where he can program this for himself.

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.