176k views
2 votes
Write a program that reads a list of words. Then, the program outputs those words and their frequencies. The input begins with an integer indicating the number of words that follow. Assume that the list will always contain less than 20 words.

1 Answer

1 vote

Answer:

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

public class FrequencyOfWords

{

public static void main(String[] args)

{

Scanner in = new Scanner(System.in);

System.out.println("Enter the integer indicating the number of words");

int n = in.nextInt();

System.out.println("Enter the string");

String[] words = new String[n];

for(int i = 0; i < n; ++i)

{

words[i] = in.next();

}

Map<String, Integer> map = new HashMap<>();

for(int i = 0; i < n; ++i)

{

if(!map.containsKey(words[i]))

{

map.put(words[i], 0);

}

map.put(words[i], map.get(words[i])+1);

}

for(Map.Entry<String, Integer> entry : map.entrySet())

{

System.out.println(entry.getKey() + " " + entry.getValue());

}

}

}

User Cathie
by
6.5k points