incomplete Dictionary.java
import java.util.*;
public class Dictionary {
private static final int INITIAL_SIZE = 5;
/*
* Declare lexicon string to store word
*/
private String[] lexicon;
public Dictionary() {
/*
* You should implement this method, the constructor
* Do not change its signature
*/
lexicon = new String[INITIAL_SIZE];
for (int i = 0; i < INITIAL_SIZE ; i++)
lexicon[i] = null;
}
public void addWord(String word) {
String[] newLexicon;
int wordCheck = 0;
while (wordCheck < lexicon.length && lexicon[wordCheck] != null)
wordCheck ++;
if (wordCheck == lexicon.length) {
newLexicon = new String[lexicon.length*2];
for (int i = 0; i < lexicon.length*2 ; i++)
newLexicon[i] = null;
for (int i = 0; i < lexicon.length ; i++)
newLexicon[i] = lexicon[i];
lexicon = newLexicon;
}
lexicon[wordCheck] = word;
}
public boolean checkWord(String word) {
/*
* You should implement this method
* Do not change its signature
*/
return false; // remove this
}
public String toString() {
String s = "";
for (int i = 0; i < lexicon.length ; i++)
s = s + lexicon[i] + ' ' ;
return s;
}
}
program to test the addWord() method
import java.io.*;
import java.util.*;
/**
* class ReadTextFileBuildDictionary
*
* This program prompts the user for a filename, reads in the filename;
* then reads every word, builds a Dictionary, and displays the contents on the console
*
* @author Terence Chan
* @version 1.0
*/
public class ReadTextFileBuildDictionary {
private static BufferedReader stdIn = new
BufferedReader(new InputStreamReader(System.in));
private static PrintWriter stdOut = new PrintWriter(System.out, true);
private static PrintWriter stdErr = new PrintWriter(System.err, true);
/**
* prompt the user for a filename, read in the filename, open the file,
* then reads and displays the contents on the console
* @param args command line arguments
* @throws IOException If an input or output exception occurred
*/
public static void main(String[] args) throws IOException {
BufferedReader inFile = null;
Dictionary dictionary = new Dictionary();
// prompt the user for filename
stdOut.print("Enter Filename : ");
stdOut.flush();
inFile = new BufferedReader(new FileReader(stdIn.readLine()));
// read and display contents
String textLine;
textLine=inFile.readLine();
//process every line in the file
while (textLine!=null) {
//use StringTokenizer to break line into words
StringTokenizer st = new StringTokenizer(textLine, " ");
while (st.hasMoreTokens()) {
//add every word
dictionary.addWord(st.nextToken());
}
textLine=inFile.readLine();
}
System.out.println("Dictionary: " + '\n' + dictionary.toString());
inFile.close();
}
}