Answer:
Step-by-step explanation:
The following function/program is written in Java. It asks the user for a sentence as an input and then splits that sentence into an array of words. Then it creates an arrayList for all of the unique words, comparing each word in the sentence with all of those in the ArrayList. If a word is found in the ArrayList it cancels the loop and moves on the next word in the sentence. Finally, it counts all of the unique words in the ArrayList and prints that total to the screen.
public static void uniqueWords() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = in.nextLine();
String words[] = sentence.split(" ");
ArrayList<String> uniqueWords = new ArrayList<>();
for (int x = 0; x < words.length; x++) {
boolean exists = false;
for (int i = 0; i < uniqueWords.size(); i++) {
if (words[x].equals(uniqueWords.get(i))) {
exists = true;
break;
}
}
if (exists == false) {
uniqueWords.add(words[x]);
}
}
System.out.println(uniqueWords.size());
}