****** PLEASE HELP******* I have to submit this by today and has to pass the tes
ID: 3833888 • Letter: #
Question
****** PLEASE HELP*******
I have to submit this by today and has to pass the test too, Here is the link to required files. I will really appreciate for help.
https://drive.google.com/open?id=0B2gb5h869g2aaVNYMjAzeDRMRjQ
Create a spell checker that uses dictionary that stores its words in a balanced binary tree.
Tasks and Requirements
NOTE: Naming is critical in the tasks and requirements described below. If the names don't match those described below exactly, your project will not be graded.
Create a copy of the Java SE Project Template. The project name must follow this pattern: {FLname}_SpellChecker_{TERM}, where {FLname} is replaced by the first letter of your first name plus your last name, and {TERM} is the current semester and year. E.g. if your name is Maria Marciano and it's Fall 2014, your project name must be MMarciano_SpellChecker_F14.
Create a package named spellchecker in your project.
BinaryTreeNode class:
Download BinaryTreeNode.java, and put it in the spellchecker package.
Your BinaryTree class must use BinaryTreeNode to store its words.
Do not modify BinaryTreeNode.java.
BasicDictionary class:
Download the Dictionary.java interface and put it in the spellchecker package.
Read the comments above each method to understand what they are supposed to do.
Create a new class named BasicDictionary in the spellchecker package. In the class creation wizard, click the Add (interface) button, and search for Dictionary. Check the "Inherited abstract methods" box. Click Finish. Eclipse will create the class and automatically add method stubs that meet the Dictionary interface.
You do not modify the Dictionary interface. You add your code to the BasicDictionary class.
BasicDictionary must use a binary tree to store the words in the dictionary. BasicDictionary can hold the root of the binary tree, but a stronger design would use a separate BinaryTree class.
You must write your own binary tree code.
BasicSpellChecker class:
Download the SpellChecker.java interface and put it in the spellchecker package.
Read the comments above each method to understand what they are supposed to do.
In BasicSpellChecker, modify the public class BasicSpellChecker to include implements SpellChecker.
You can use Eclipse's QuickFix support to add the required methods to BasicSpellChecker.
You do not modify the SpellChecker interface. You add your spell-checking code to BasicSpellChecker's methods.
Add the unit testing classes. These classes will be used to test the code that you write.
Create a new package in the src folder called sbccunittest. To be clear: sbccunittest should be a child of the src folder, not of the spellchecker package.
Download SpellCheckerTester.java into sbccunittest.
Download test_files.zip into your project root and unzip them into your project's root folder.
Spell-checking notes
Be sure to read the SpellChecker.spellCheck() documentation carefully. It specifies the regular expression that you must use for iterating through words in the document.
It also describes an instance variable of BasicSpellChecker that you need to create and update - the current spell checking index.
Also be sure to read the SpellChecker.replaceText() documentation carefully. It describes how the spell checking index is to be adjusted when replaceText() is called.
Note that the test documents are Windows files, which means that each line ends with (i.e. two characters).
Ignore case when comparing words.
Unit Testing
Debug all java compilation Errors (see the Problems view). The unit tests can't be run until these errors are fixed.
In the Package Explorer, right-click on the sbccunittest package | Run As... | JUnit Test.
Initially, all of the tests will probably fail. However, as you add functionality to the BasicDictionary class, tests will begin to pass.
Work on BasicDictionary first. Continue adding functionality to the BasicDictionary until all of the dictionary tests (see Scoring section below) pass. Then start working on BasicSpellChecker and its associated tests.
There is no user interface requirement for this assignment. However, you might find it interesting to build a simple console interface that allows the user to specify a dictionary and a text document to spell check. When an unknown word is found, give the user options to ignore the word, change it themselves, replace it with the preceeding/succeeding word, or end the spell checking. When spell checking is completed, overwrite the original text document with the spell-checked version.
*** When importing the dictionary, build a complete tree
Explanation / Answer
SpellCheckerTester.java
package sbccunittest;
import static org.junit.Assert.*;
import java.io.*;
import java.util.*;
import org.apache.commons.io.*;
import org.junit.*;
import spellchecker.*;
import spellchecker.Dictionary;
public class SpellCheckerTester {
public static String newline = System.getProperty("line.separator");
public static int totalScore = 0;
public static int extraCredit = 0;
@BeforeClass
public static void beforeTesting() {
totalScore = 0;
extraCredit = 0;
}
@AfterClass
public static void afterTesting() {
System.out.println("Estimated score (assuming no late penalties, etc.) = " + totalScore);
System.out.println("Estimated extra credit (assuming on time submission) = " + extraCredit);
}
@Test(timeout = 10000)
public void testImportFile() throws Exception {
Dictionary dictionary = new BasicDictionary();
dictionary.importFile("full_dictionary.txt");
assertNotNull("Dictionary.getRoot() should not be null.", dictionary.getRoot());
int depth = getTreeDepth(dictionary);
int maxDepth = 100;
if (depth > maxDepth)
fail("The tree depth is " + depth + " is greater than the maximum allowed depth of " + maxDepth + ".");
dictionary.save("full_dictionary.pre");
String s = FileUtils.readFileToString(new File("full_dictionary.pre"));
String[] parts = s.split(" ");
assertEquals(175169, parts.length);
totalScore += 12;
}
@Test(timeout = 10000)
public void testImportFileCompleteTree() throws Exception {
Dictionary dictionary = new BasicDictionary();
dictionary.importFile("full_dictionary.txt");
assertNotNull("Dictionary.getRoot() should not be null.", dictionary.getRoot());
int depth = getTreeDepth(dictionary);
int maxDepth = 18;
if (depth > maxDepth)
fail("The tree depth is " + depth + ", which is greater than the maximum allowed depth of " + maxDepth
+ ".");
dictionary.save("full_dictionary.pre");
String s = FileUtils.readFileToString(new File("full_dictionary.pre"));
String[] parts = s.split(" ");
assertEquals(175169, parts.length);
extraCredit += 5;
}
int treeDepth;
public int getTreeDepth(Dictionary dictionary) {
treeDepth = 0;
goDeeper(dictionary.getRoot(), 0);
return treeDepth;
}
private void goDeeper(BinaryTreeNode node, int depth) {
if (node != null) {
depth++;
if (depth > treeDepth)
treeDepth = depth;
if (node.left != null)
goDeeper(node.left, depth);
if (node.right != null)
goDeeper(node.right, depth);
}
}
@Test(timeout = 10000)
public void testLoad() throws Exception {
Dictionary dictionary = new BasicDictionary();
dictionary.load("dict_14.pre");
assertNotNull("Dictionary.getRoot() should not be null.", dictionary.getRoot());
int depth = getTreeDepth(dictionary);
assertEquals(6, depth);
totalScore += 8;
}
@Test(timeout = 10000)
public void testSave() throws Exception {
Dictionary dictionary = new BasicDictionary();
String[] words = new String[] { "bull", "are", "genetic", "cotton", "dolly", "florida", "each", "bull" };
for (String word : words)
dictionary.add(word);
dictionary.save("test_save.pre");
String s = FileUtils.readFileToString(new File("test_save.pre"));
String[] parts = s.split(" ");
assertEquals(words.length - 1, parts.length);
for (int ndx = 0; ndx < parts.length; ndx++)
assertEquals(words[ndx], parts[ndx].trim().toLowerCase());
totalScore += 8;
}
@Test(timeout = 10000)
public void testFind() throws Exception {
Dictionary dictionary = new BasicDictionary();
String dictionaryPath = "dict_14.pre";
dictionary.load(dictionaryPath);
checkWord(dictionary, dictionaryPath, "cotton", null);
checkWord(dictionary, dictionaryPath, "CottoN", null);
checkWord(dictionary, dictionaryPath, "Cotto", new String[] { "bull", "cotton" });
checkWord(dictionary, dictionaryPath, "mit", new String[] { "life", "mite" });
checkWord(dictionary, dictionaryPath, "mite", null);
checkWord(dictionary, dictionaryPath, "just", null);
totalScore += 8;
}
private void checkWord(Dictionary dictionary, String dictionaryPath, String word, String[] expectedResult) {
String[] result = dictionary.find(word);
if (expectedResult != null) {
if (result != null) {
assertEquals(expectedResult[0], result[0]);
assertEquals(expectedResult[1], result[1]);
} else
fail("Didn't find " + word + " in " + dictionaryPath);
} else {
if (result != null) {
fail("The dictionary returned " + (result.length > 0 ? result[0] : "an empty array")
+ " but should have returned null because " + word + " does exist in " + dictionaryPath);
}
}
}
@Test
public void testLoadDocument() throws Exception {
String dictionaryText = FileUtils.readFileToString(new File("small_dictionary.txt"));
String[] words = dictionaryText.split(newline);
Random rng = new Random();
String doc = words[rng.nextInt(words.length)].trim() + " "
+ words[rng.nextInt(words.length)].trim() + " "
+ words[rng.nextInt(words.length)].trim() + " "
+ words[rng.nextInt(words.length)].trim() + " "
+ words[rng.nextInt(words.length)].trim();
FileUtils.write(new File("random_doc.txt"), doc);
SpellChecker basicSpellChecker = new BasicSpellChecker();
basicSpellChecker.loadDocument("random_doc.txt");
String text = basicSpellChecker.getText();
assertEquals(doc, text);
totalScore += 2;
}
@Test
public void testSpellCheckWithOneUnknownWord() throws Exception {
SpellChecker basicSpellChecker = new BasicSpellChecker();
String dictionaryImportPath = "small_dictionary.txt";
String dictionaryPath = "small_dictionary.pre";
String documentPath = "small_document_one_unknown.txt";
basicSpellChecker.importDictionary(dictionaryImportPath);
basicSpellChecker.saveDictionary(dictionaryPath);
basicSpellChecker.loadDocument(documentPath);
String[] result;
result = basicSpellChecker.spellCheck(false);
if (result == null)
fail("There should be one unknown word in " + documentPath + " when the dictionary is "
+ dictionaryImportPath);
else {
assertEquals("explosins", result[0]);
assertEquals("87", result[1]);
assertEquals("ever", result[2]);
assertEquals("explosions", result[3]);
}
totalScore += 6;
}
@Test
public void testSpellCheckReplaceOneUnknownWord() throws Exception {
SpellChecker basicSpellChecker = new BasicSpellChecker();
String dictionaryImportPath = "small_dictionary.txt";
String dictionaryPath = "small_dictionary.pre";
String documentPath = "small_document_one_unknown.txt";
basicSpellChecker.importDictionary(dictionaryImportPath);
basicSpellChecker.saveDictionary(dictionaryPath);
basicSpellChecker.loadDocument(documentPath);
String[] result;
// Spell-check and find one word misspelled.
result = basicSpellChecker.spellCheck(false);
if (result == null)
fail("There should be one unknown word in " + documentPath + " when the dictionary is "
+ dictionaryImportPath);
else {
assertEquals("explosins", result[0]);
assertEquals("87", result[1]);
assertEquals("ever", result[2]);
assertEquals("explosions", result[3]);
}
// Replace it with the second suggestion.
int startIndex = Integer.parseInt(result[1]);
int endIndex = startIndex + result[0].length();
basicSpellChecker.replaceText(startIndex, endIndex, result[3]);
// Check against corrected.
String text = basicSpellChecker.getText();
String expected = FileUtils.readFileToString(new File("small_document_one_unknown_corrected.txt"));
assertEquals(expected, text);
totalScore += 6;
}
@Test
public void testSpellCheckNoUnknownWords() throws Exception {
SpellChecker basicSpellChecker = new BasicSpellChecker();
String dictionaryImportPath = "small_dictionary.txt";
String dictionaryPath = "small_dictionary.pre";
String documentPath = "small_document.txt";
basicSpellChecker.importDictionary(dictionaryImportPath);
basicSpellChecker.saveDictionary(dictionaryPath);
basicSpellChecker.loadDocument(documentPath);
String[] result;
result = basicSpellChecker.spellCheck(false);
if (result != null)
fail("There should be no unknown words in " + documentPath + " when the dictionary is " + dictionaryPath);
totalScore += 4;
}
@Test
public void testSpellCheckReplaceUnknowns() throws Exception {
SpellChecker basicSpellChecker = new BasicSpellChecker();
String dictionaryImportPath = "small_dictionary.txt";
String dictionaryPath = "small_dictionary.pre";
String documentPath = "small_document_four_unknown.txt";
basicSpellChecker.importDictionary(dictionaryImportPath);
basicSpellChecker.saveDictionary(dictionaryPath);
basicSpellChecker.loadDocument(documentPath);
String[] result;
// Find first unknown
result = basicSpellChecker.spellCheck(false);
if (result == null)
fail("Failed to find the first unknown word in " + documentPath + " when the dictionary is "
+ dictionaryImportPath);
else {
assertEquals("explosins", result[0]);
assertEquals("87", result[1]);
assertEquals("ever", result[2]);
assertEquals("explosions", result[3]);
}
// Replace it with the successor word
int startIndex = Integer.parseInt(result[1]);
int endIndex = startIndex + result[0].length();
basicSpellChecker.replaceText(startIndex, endIndex, result[3]);
// find the 2nd unknown (the word "which")
result = basicSpellChecker.spellCheck(true);
if (result == null)
fail("Failed to find the second unknown word in " + documentPath + " when the dictionary is "
+ dictionaryImportPath);
else {
assertEquals("which", result[0]);
assertEquals("130", result[1]);
assertEquals("use", result[2]);
assertEquals("with", result[3]);
}
// Add this word to the dictionary
String wordToAdd = result[0];
basicSpellChecker.addWordToDictionary(result[0]);
// find the 3rd unknown (the word "vast")
result = basicSpellChecker.spellCheck(true);
if (result == null)
fail("Failed to find the third unknown word in " + documentPath + " when the dictionary is "
+ dictionaryImportPath);
else {
assertEquals("vast", result[0]);
assertEquals("275", result[1]);
assertEquals("use", result[2]);
assertEquals("which", result[3]);
}
// Find third unknown
result = basicSpellChecker.spellCheck(true);
if (result == null)
fail("Failed to find the fourth unknown word in " + documentPath + " when the dictionary is "
+ dictionaryImportPath);
else {
assertEquals("cuosmos", result[0]);
assertEquals("280", result[1]);
assertEquals("cosmos", result[2]);
assertEquals("dozen", result[3]);
}
// Replace it with the predecessor word
startIndex = Integer.parseInt(result[1]);
endIndex = startIndex + result[0].length();
basicSpellChecker.replaceText(startIndex, endIndex, result[2]);
// Verify document is correct
String expectedText = FileUtils.readFileToString(new File("small_document_four_unknown_corrected.txt"));
String actualText = basicSpellChecker.getText();
assertEquals(expectedText, actualText);
// Verify the saved document is correct
basicSpellChecker.saveDocument("small_document_four_unknown_after_spellchecking.txt");
actualText = FileUtils.readFileToString(new File("small_document_four_unknown_after_spellchecking.txt"));
assertEquals(expectedText, actualText);
// Verify the dictionary is correct
basicSpellChecker.saveDictionary("small_dictionary_after_spellchecking.pre");
String dictText = FileUtils.readFileToString(new File("small_dictionary_after_spellchecking.pre"));
if (!dictText.contains(wordToAdd))
fail("Dictionary file didn't contain " + wordToAdd + ".");
totalScore += 4;
}
@Test
public void testSpellCheckNoSuccessor() throws Exception {
SpellChecker basicSpellChecker = new BasicSpellChecker();
String dictionaryImportPath = "small_dictionary.txt";
String dictionaryPath = "small_dictionary.pre";
String documentPath = "small_document_test_no_successor.txt";
basicSpellChecker.importDictionary(dictionaryImportPath);
basicSpellChecker.saveDictionary(dictionaryPath);
basicSpellChecker.loadDocument(documentPath);
String[] result;
// Find first unknown
result = basicSpellChecker.spellCheck(false);
if (result == null)
fail("Failed to find the first unknown word in " + documentPath + " when the dictionary is "
+ dictionaryImportPath);
else {
assertEquals("zebras", result[0]);
assertEquals("87", result[1]);
assertEquals("with", result[2]);
assertEquals("", result[3]);
}
totalScore += 2;
}
}
BasicDictionary.java
package spellchecker;
import java.io.*;
import java.util.*;
import org.apache.commons.io.*;
public class BasicDictionary implements Dictionary {
private BinaryTree binaryWordTree = new BinaryTree();
/**
* Replaces the current dictionary with words imported from the specified text file. Words in the file are in
* lexicographical (ASCII) order, one word per line.
*
* @param filename
* Name (possibly including a path) of the file to import.
* @throws Exception
*/
public void importFile(String filename) throws Exception {
ArrayList<String> lines = (ArrayList<String>) FileUtils.readLines(new File(filename));
binaryWordTree = new BinaryTree();
for (int i = 0; i < lines.size(); i++) {
binaryWordTree.add(lines.get(i).trim());
}
}
/**
* Loads the specified file from a previously saved dictionary tree file. The file format is text, with one word per
* line.
*
* @param filename
* Name (possibly including a path) of the file to load from.
* @throws Exception
*/
public void load(String filename) throws Exception {
ArrayList<String> lines = (ArrayList<String>) FileUtils.readLines(new File(filename));
binaryWordTree = new BinaryTree();
for (int i = 0; i < lines.size(); i++) {
binaryWordTree.add(lines.get(i).trim());
}
}
/**
* Saves the dictionary tree to the specified file in preorder. The file format is text, with one word per line.
*
* @param filename
* Name (possibly including a path) of the file to save to. If the file exists, it is overwritten.
* @throws Exception
*/
public void save(String filename) throws Exception {
ArrayList<String> list = binaryWordTree.transverseInPreorder();
FileUtils.writeLines(new File(filename), list);
}
/**
*
* @param word
* @return If the word is <b>found</b> this method returns <b>null</b>. Otherwise, it returns a String array
* organized as follows:
*
*/
public String[] find(String word) {
if (binaryWordTree.find(word) != null)
return null;
else
return new String[1];
}
/**
* Adds the given word to the dictionary's binary tree. Duplicates are ignored.
*
* @param word
*/
public void add(String word) {
binaryWordTree.add(word);
}
/**
*
* @return Returns a reference to the root node of the binary tree.
*/
public BinaryTreeNode getRoot() {
return binaryWordTree.getRoot();
}
/**
*
* @return Returns the number of words in the dictionary.
*/
public int getCount() {
return binaryWordTree.getCount();
}
}
BasicSpellChecker.java
package spellchecker;
import java.io.*;
import java.util.regex.*;
import org.apache.commons.io.*;
public class BasicSpellChecker implements SpellChecker {
private static final String REGEX = "\b[\w']+\b";
BasicDictionary dictionary = new BasicDictionary();
Pattern regex = Pattern.compile(REGEX);
Matcher matcher;
String text;
int index;
/**
* Replaces the current dictionary with words imported from the specified text file. Words in the file are in
* lexicographical (ASCII) order, one word per line.
*
* @param filename
* Name (possibly including a path) of the file to import.
* @throws Exception
*/
public void importDictionary(String filename) throws Exception {
dictionary.importFile(filename);
}
/**
* Loads the specified file from a previously saved dictionary tree file. The file format is text, with one word per
* line.
*
* @param filename
* Name (possibly including a path) of the file to load from.
* @throws Exception
*/
public void loadDictionary(String filename) throws Exception {
dictionary.load(filename);
}
/**
* Saves the dictionary tree to the specified file in preorder. The file format is text, with one word per line.
*
* @param filename
* Name (possibly including a path) of the file to save to. If the file exists, it is overwritten.
* @throws Exception
*/
public void saveDictionary(String filename) throws Exception {
dictionary.save(filename);
}
/**
* Loads the specified text document.
*
* @param filename
* @throws Exception
*/
public void loadDocument(String filename) throws Exception {
text = FileUtils.readFileToString(new File(filename));
matcher = regex.matcher(text);
}
/**
* Saves the specified text document.
*
* @param filename
* @throws Exception
*/
public void saveDocument(String filename) throws Exception {
FileUtils.write(new File(filename), text);
}
/**
*
* @return Returns the text in the document.
*/
public String getText() {
return text;
}
/**
* @param continueFromPrevious
* If false, a new spell check is started from the first character of the document. If true, the spell
* check continues from it's current location.
* @return If no unknown word is found this method returns null. Otherwise, it returns a String array organized as
* follows:
*
*/
public String[] spellCheck(boolean continueFromPrevious) {
int start = 0;
int end = 0;
while (matcher.find(start)) {
start = matcher.start();
end = matcher.end();
String word = text.substring(start, end);
String[] words = dictionary.find(word);
if (words != null)
return words;
}
;
}
/**
* Adds the given word to the dictionary's tree
*
* @param word
*/
public void addWordToDictionary(String word) {
dictionary.add(word);
}
/**
*
* @param startIndex
* Index of the first character to replace.
* @param endIndex
* Index of the character <b>after</b> the last character to replace.
* @param replacementText
*/
public void replaceText(int startIndex, int endIndex, String replacementText) {
StringBuilder. text = "oeijr";
text.replac
}
}
BasicSpellChecker.java
package spellchecker;
import java.io.*;
import java.util.regex.*;
import org.apache.commons.io.*;
public class BasicSpellChecker implements SpellChecker {
private static final String REGEX = "\b[\w']+\b";
BasicDictionary dictionary = new BasicDictionary();
Pattern regex = Pattern.compile(REGEX);
Matcher matcher;
String text;
int index;
/**
* Replaces the current dictionary with words imported from the specified text file. Words in the file are in
* lexicographical (ASCII) order, one word per line.
*
* @param filename
* Name (possibly including a path) of the file to import.
* @throws Exception
*/
public void importDictionary(String filename) throws Exception {
dictionary.importFile(filename);
}
/**
* Loads the specified file from a previously saved dictionary tree file. The file format is text, with one word per
* line.
*
* @param filename
* Name (possibly including a path) of the file to load from.
* @throws Exception
*/
public void loadDictionary(String filename) throws Exception {
dictionary.load(filename);
}
/**
* Saves the dictionary tree to the specified file in preorder. The file format is text, with one word per line.
*
* @param filename
* Name (possibly including a path) of the file to save to. If the file exists, it is overwritten.
* @throws Exception
*/
public void saveDictionary(String filename) throws Exception {
dictionary.save(filename);
}
/**
* Loads the specified text document.
*
* @param filename
* @throws Exception
*/
public void loadDocument(String filename) throws Exception {
text = FileUtils.readFileToString(new File(filename));
matcher = regex.matcher(text);
}
/**
* Saves the specified text document.
*
* @param filename
* @throws Exception
*/
public void saveDocument(String filename) throws Exception {
FileUtils.write(new File(filename), text);
}
/**
*
* @return Returns the text in the document.
*/
public String getText() {
return text;
}
/**
*
* The method returns when the first unknown word is located or when the end of the document is reached (whichever
* comes first). The index of the character after the unknown word is retained for use as the starting index for
* subsequent calls to spellCheck where continueFromPrevious is true.
*
* @param continueFromPrevious
* If false, a new spell check is started from the first character of the document. If true, the spell
* check continues from it's current location.
* @return If no unknown word is found this method returns null. Otherwise, it returns a String array organized as
* follows:
*
*/
public String[] spellCheck(boolean continueFromPrevious) {
int start = 0;
int end = 0;
while (matcher.find(start)) {
start = matcher.start();
end = matcher.end();
String word = text.substring(start, end);
String[] words = dictionary.find(word);
if (words != null)
return words;
}
;
}
/**
* Adds the given word to the dictionary's tree
*
* @param word
*/
public void addWordToDictionary(String word) {
dictionary.add(word);
}
/**
*
* @param startIndex
* Index of the first character to replace.
* @param endIndex
* Index of the character <b>after</b> the last character to replace.
* @param replacementText
*/
public void replaceText(int startIndex, int endIndex, String replacementText) {
StringBuilder. text = "oeijr";
text.replac
}
}
BinaryTreeNode.java
package spellchecker;
public class BinaryTreeNode {
public BinaryTreeNode left;
public BinaryTreeNode right;
public String value;
BinaryTreeNode(String value) {
this.value = value;
}
BinaryTreeNode(BinaryTreeNode node) {
left = node.left;
right = node.right;
value = node.value;
}
}
BinaryTree.java
package spellchecker;
import java.util.*;
public class BinaryTree {
private BinaryTreeNode root;
private int count = 0;
public BinaryTree() {
}
public BinaryTree(String[] words) {
for (String word : words) {
add(word);
}
}
public BinaryTree(ArrayList<String> words) {
for (String word : words) {
add(word);
}
}
/**
* Checks if word1 is lexigraphically prior to word2.
*
* @param word1
* @param word2
* @return True if word1 comes before word2, false if word1 comes after word2
* @throws IllegalArgumentException
* if the words are equal.
*/
private static boolean areWordsInOrder(String word1, String word2) throws IllegalArgumentException {
int compare = word1.compareTo(word2);
if (compare < 0) {
// word1 comes before word2
return true;
} else if (compare > 0) {
// word1 comes after word2
return false;
} else {
throw new IllegalArgumentException("Words are equal: " + word1 + word2);
}
}
public void add(String word) {
count++;
word = word.trim();
if (root == null) {
root = new BinaryTreeNode(word);
return;
}
BinaryTreeNode cur = root;
while (true) {
if (areWordsInOrder(word, cur.value)) {
if (cur.left != null) {
cur = cur.left;
continue;
} else {
cur.left = new BinaryTreeNode(word);
return;
}
} else {
if (cur.right != null) {
cur = cur.right;
continue;
} else {
cur.right = new BinaryTreeNode(word);
return;
}
}
}
}
/**
* @param word
* @return If the word is <b>found</b> this method returns <b>null</b>. Otherwise, it returns a String array
* organized as follows:
*/
public String[] find(String word) {
word = word.trim();
BinaryTreeNode cur = root;
Stack<BinaryTreeNode> stack = new Stack<>();
while (cur != null) {
stack.push(cur);
if (word.equals(cur.value)) {
// Item is found!
return null;
}
if (areWordsInOrder(word, cur.value)) {
// word comes lexigraphically before cursor
cur = cur.left;
} else {
// word comes lexigraphically after cursor
cur = cur.right;
}
}
String[] neighbors = new String[2];
BinaryTreeNode leftCur = cur;
while (neighbors[0] != null && neighbors[1] != null) {
while (leftCur.left == null) {
}
}
return null;
}
public ArrayList<String> transverseInPreorder() {
ArrayList<String> list = new ArrayList<>();
Stack<BinaryTreeNode> rightBranchesStack = new Stack<>();
BinaryTreeNode cur = root;
while (cur != null) {
list.add(cur.value);
// If there is a right branch to the current node, add it to the stack
if (cur.right != null) {
rightBranchesStack.add(cur.right);
}
if (cur.left != null) {
cur = cur.left;
} else if (!rightBranchesStack.isEmpty()) {
cur = rightBranchesStack.pop();
} else {
return list;
}
}
throw new RuntimeException("Programming error. THis line should not be reached.");
}
public int getCount() {
return count;
}
public BinaryTreeNode getRoot() {
return root;
}
}
Dictionary.java
package spellchecker;
public interface Dictionary {
/**
*
* @param filename
* Name (possibly including a path) of the file to import.
* @throws Exception
*/
public void importFile(String filename) throws Exception;
/**
* Loads the specified file from a previously saved dictionary tree file. The file format is text, with one word per
* line.
*
* @param filename
* Name (possibly including a path) of the file to load from.
* @throws Exception
*/
public void load(String filename) throws Exception;
/**
* Saves the dictionary tree to the specified file in preorder. The file format is text, with one word per line.
*
* @param filename
* Name (possibly including a path) of the file to save to. If the file exists, it is overwritten.
* @throws Exception
*/
public void save(String filename) throws Exception;
/**
*
* @param word
* @return If the word is <b>found</b> this method returns <b>null</b>. Otherwise, it returns a String array
* organized as follows:
*/
public String[] find(String word);
/**
* Adds the given word to the dictionary's binary tree. Duplicates are ignored.
*
* @param word
*/
public void add(String word);
/**
*
* @return Returns a reference to the root node of the binary tree.
*/
public BinaryTreeNode getRoot();
/**
*
* @return Returns the number of words in the dictionary.
*/
public int getCount();
}
SpellChecker.java
package spellchecker;
public interface SpellChecker {
/**
* @param filename
* Name (possibly including a path) of the file to import.
* @throws Exception
*/
public void importDictionary(String filename) throws Exception;
/**
*
*
* @param filename
* Name (possibly including a path) of the file to load from.
* @throws Exception
*/
public void loadDictionary(String filename) throws Exception;
/**
* Saves the dictionary tree to the specified file in preorder. The file format is text, with one word per line.
*
* @param filename
* Name (possibly including a path) of the file to save to. If the file exists, it is overwritten.
* @throws Exception
*/
public void saveDictionary(String filename) throws Exception;
/**
* Loads the specified text document.
*
* @param filename
* @throws Exception
*/
public void loadDocument(String filename) throws Exception;
/**
* Saves the specified text document.
*
* @param filename
* @throws Exception
*/
public void saveDocument(String filename) throws Exception;
/**
*
* @return Returns the text in the document.
*/
public String getText();
/**
*
* @param continueFromPrevious
* If false, a new spell check is started from the first character of the document. If true, the spell
* check continues from it's current location.
* @return If no unknown word is found this method returns null. Otherwise, it returns a String array organized as
* follows:
*
*
*/
public String[] spellCheck(boolean continueFromPrevious);
/**
* Adds the given word to the dictionary's tree
*
* @param word
*/
public void addWordToDictionary(String word);
/**
*
* @param startIndex
* Index of the first character to replace.
* @param endIndex
* Index of the character <b>after</b> the last character to replace.
* @param replacementText
*/
public void replaceText(int startIndex, int endIndex, String replacementText);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.