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 fewer than 20 words. Ex: If the input is: 5 hey hi Mark hi mark the output is: hey - 1 hi - 2 Mark - 1 hi - 2 mark - 1 Hint: Use two arrays, one array for the strings and one array for the frequencies.
Write a
Ex: If the input is:
5 hey hi Mark hi mark
the output is:
hey - 1 hi - 2 Mark - 1 hi - 2 mark - 1
Hint: Use two arrays, one array for the strings and one array for the frequencies.
Explanation
Import the
java.util.Scanner
class to read input from the console.In the
main
method:- Create a
Scanner
object namedinput
to read input from the user.
- Create a
Read the number of words to be entered from the user:
int numWords = input.nextInt();
: Read an integer representing the number of words.input.nextLine();
: Consume the newline character after the integer.
Loop through the input words and process them:
- Read the word using
String word = input.next();
- Read the word using
Check if the word is already in the
words
array:- Use another
for
loop to iterate through the words stored in thewords
array (from index 0 toi - 1
).
- Use another
The program repeats the output step for all words, ensuring that each unique word is displayed along with its count.
The program then finishes execution.
Step by step
Solved in 3 steps with 2 images