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.