Skip to content

Instantly share code, notes, and snippets.

@Hulzenga
Last active August 29, 2015 14:01
Show Gist options
  • Save Hulzenga/577c05be1fb5b23e5512 to your computer and use it in GitHub Desktop.
Save Hulzenga/577c05be1fb5b23e5512 to your computer and use it in GitHub Desktop.
/*
Author: Oscar Bell
Date: 9th May 2014
Description: Program to count the occurrences of words in a string
*/
import java.util.*;
import java.util.Map.Entry;
public class WordOccurrence {
//-----------------------------------------------------------------------------
public static Set<String> commonWords = new HashSet<>();
{
commonWords.add("the");
//add other common words here
}
//-----------------------------------------------------------------------------
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String count;
// Words between quotation marks are the instructions presented in output
System.out.print("Please enter a string: ");
count = in.nextLine();
// Removes punctuation so that words with and without punctuation are counted together
count = count.replaceAll("[^a-zA-Z ]", "");
findWordOccurrences(count);
}
private static void findWordOccurrences(final String str) {
// Map containing word usage
Map<String, Integer> wordArray = new HashMap<>();
// The array of all words in the string
String[] allWords;
// Converts to lower case so words with different cases are counted together
String essay = str.toLowerCase();
allWords = essay.split(" ");
for (String allWord : allWords) {
Integer count = wordArray.get(allWord);
// Count won't be null if the word already exists in map
//-----------------------------------------------------------------------------
if (count != null) {
if (!commonWords.contains(count)) {
//-----------------------------------------------------------------------------
wordArray.put(allWord, count + 1);
}
} else {
wordArray.put(allWord, 1);
}
}
printWordOccurrences(wordArray);
}
//Produces table of results
private static void printWordOccurrences(Map<String, Integer> wordCount) {
System.out.println("Word\t\tCount");
for(Entry<String, Integer> entry : wordCount.entrySet())
{
System.out.println(entry.getKey() + "\t\t" + entry.getValue());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment