Just what the title says, this code counts the total of words in a text and count the words without repeating. For example:
My name is Perez Perez
total words: 5
total without repeating words: 4 (since Perez appear two times)
Hope you got it, now the code:
// don't forget to add the required libraries
public void countWords(String text1 ){
// text1 is the text whose we want to get the count of words
ArrayList<String> wordArray = new ArrayList<String>();
//split the text in an array using spaces to get the words
String[] words = text1.split(" ");
//add the word to an ArrayList
wordArray.addAll(Arrays.asList(words));
//Create a HashSet
HashSet hs = new HashSet();
//next line add to the HashSet the words without repeating
hs.addAll(wordArray);
//clean the Array
wordArray.clear();
//add to the Array the words without repeating
wordArray.addAll(hs);
//print the output
System.out.print("total words: "+words.length
);
System.out.print("total without repeating words: "+wordArray.size()
);
}