Skip to content

Instantly share code, notes, and snippets.

@Tejash241
Created August 29, 2014 15:03
Show Gist options
  • Save Tejash241/bbc9b3164acb5e56ec05 to your computer and use it in GitHub Desktop.
Save Tejash241/bbc9b3164acb5e56ec05 to your computer and use it in GitHub Desktop.
A java programme to count the number of occurrences of each word in a sentence
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
public class NumberOfOccurencesOfWordsInSentence {
public static HashMap <Integer, String> stringMap = new HashMap<Integer, String>();
public static HashMap <Integer, Integer> countMap = new HashMap<Integer, Integer>();
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = in.nextLine();
ArrayList<String> words = separateWords(sentence);
addWordsToMap(words);//arranges the words in a HashMap
//printWordsInMap();
returnCountOfWords();
}
//this function separates the words in the sentence and stores them in an ArrayList.
//word separating is done by finding blank spaces between 2 words
public static ArrayList<String> separateWords(String sentence){
ArrayList <String> words = new ArrayList<String>();
int startIndex = 0;
for (int i = 0; i < sentence.length(); i++) {
if(sentence.charAt(i) == ' '){ //if blank space encountered
words.add(sentence.substring(startIndex, i)); //finish this word and add it to the List
startIndex = i+1;//start a new word
}
}
words.add(sentence.substring(startIndex));//add the last word in the sentence
return words;
}
public static void addWordsToMap(ArrayList<String> words){
int key;
for (int i = 0; i < words.size(); i++) {
key = calculateAscii(words.get(i));
stringMap.put(key, words.get(i));
if(countMap.get(key) == null){
countMap.put(key, 0);
}
countMap.put(key, countMap.get(key)+1);
}
}
//this function returns the ASCII value of the word passed as argument
public static int calculateAscii(String s){
int value = 0;
for (int i = 0; i < s.length(); i++) {
value += (int)s.charAt(i);
}
return value;
}
//this function was made for debugging purposes
/*public static void printWordsInMap(){
Iterator iterator = stringMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry)iterator.next();
System.out.println(entry.getKey() + " key has " + entry.getValue() + " value");
}
}*/
//this function iterates through the HashMap and gives the output
public static void returnCountOfWords(){
Iterator iterator = countMap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry = (Map.Entry)iterator.next();
System.out.println("The count of " + stringMap.get(entry.getKey()) + " is : " + entry.getValue());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment