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);
        System.out.print('\n'); 
        phrase[i] = input.nextLine();
        System.out.print('\n');
        System.out.print(phrase[i].toString());
        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;
        }    


        System.out.print('\n');
        System.out.print(total);


    }

}

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.

Recommended Answers

All 2 Replies

Hi,

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) {
    Arrays.sort(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.

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.