/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package wordbag; /** * * @author kvaradar */ public class WordBag { MyWord [] myArray; static int defaultCapacity = 1000; int numWords; //how many distinct words public WordBag() { this(defaultCapacity); } public WordBag(int x) { if (x < defaultCapacity) x = defaultCapacity; myArray = new MyWord [x]; numWords = 0; } public void addOccurance(String word) { int currFreq; int index = getIndexOf(word); if (index == numWords) { myArray[index] = new MyWord(word); numWords++; } else { currFreq = myArray[index].getFrequency(); currFreq = currFreq + 1; myArray[index].setFrequency(currFreq); } } public void removeOccurance(String word) { int index = getIndexOf(word); if (index == numWords) return; int currFreq = myArray[index].getFrequency(); if (currFreq > 1) { myArray[index].setFrequency(currFreq - 1); } else { for (int j = index + 1; j < numWords; j++) { myArray[j-1] = myArray[j]; } numWords--; } } public String mostFrequent(){ MyWord mF = myArray[0]; for (int i = 1; i < numWords; i ++) { if (myArray[i].getFrequency() > mF.getFrequency()) mF = myArray[i]; } return mF.getWord(); } public int numberOfWords() { //return number of distinct words return numWords; } public int getFrequency(String word) { int index = getIndexOf(word); if (index < numWords) { return myArray[index].getFrequency(); } return -1; } private int getIndexOf(String word) { int index = numWords; for (int i = 0; i < numWords; i++) { if (myArray[i].getWord().equals(word)) { index = i; break; } } return index; } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here WordBag bg = new WordBag(); bg.addOccurance("it"); bg.addOccurance("long"); bg.addOccurance("it"); } }