JAVA* I need help with this program: I have some of it coded up, and I can\'t fi
ID: 3572464 • Letter: J
Question
JAVA* I need help with this program: I have some of it coded up, and I can't figure out the rest of it. I had gotten 1a - 1c and the output was fine, and in 1d, I messed around with the nested node class visibility modifers, and it won't take the input correctly anymore.I need this project done by tomorrow night, and I haven't the slightest clue how to go about doing part 2 also.I will be staying up all night, so ANY HELP WOULD BE APPRECIATED Here is the assignment:
MY BSTSPELLCHECKER CLASS:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
@SuppressWarnings("rawtypes")
public class BSTSpellChecker<E> extends BinarySearchTree{
BinarySearchTree wordList = new BinarySearchTree();
@SuppressWarnings("unchecked")
public boolean contains(String s){
return wordList.contains(s);
}
@SuppressWarnings("unchecked")
public void addFile(File f) throws FileNotFoundException{
Scanner s = new Scanner(new FileReader(f));
while (s.hasNextLine()){
String line = s.nextLine();
wordList.addNR(line);
}
s.close();
}
@SuppressWarnings("unchecked")
public void addFileBalanced(File f) throws FileNotFoundException{
Scanner s = new Scanner (new FileReader(f));
ArrayList<E> words = new ArrayList<E>();
while (s.hasNextLine()){
String line = s.nextLine();
words.add((E) line);
}
s.close();
String[] WL = words.toArray(new String[words.size()]);
int size = WL.length;
root = wordList.sortedArraytoBST(WL, 0, size - 1);
}
public void inOT(){
wordList.inOrderTraversal();
}
@SuppressWarnings("unchecked")
public static void main(String[] args){
File file = new File("C:\Users\JKP2\Documents\workspace\Comp2150Project3\Project3_wordlist.txt");
BSTSpellChecker<String> words = new BSTSpellChecker();
try {
words.addFileBalanced(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//words.addFile(file);
//words.inOT();
System.out.println("DONE!");
System.out.println("Contains 'zygote': " + words.contains("zygote"));
System.out.println("Contains 'aah': " + words.contains("aah"));
System.out.println("Contains 'zygota': " + words.contains("zygota"));
}
}
MY BST CLASS:
public class BinarySearchTree<E extends Comparable<E>> {
static class Node<E> {
private E data;
Node(E data) {
this.data = data;
setLeft(null);
setRight(null);
}
private Node(E data, Node<E> left, Node<E> right) {
this.data = data;
this.setLeft(left);
this.setRight(right);
}
public void setLeft(Node<E> left) {
}
public void setRight(Node<E> right) {
}
public Node<E> getLeft() {
// TODO Auto-generated method stub
return null;
}
}
protected Node<E> root; // keeps track of the root node
// Wrapper method for add
public void add(E newItem) {
if (root == null)
root = new Node<>(newItem, null, null);
else
add(newItem, root);
}
// Recursive add method.
private void add(E newItem, Node<E> where) {
int c = newItem.compareTo(where.data);
if (c < 0 && where.getLeft() == null) // base case - newItem < where.data, and there is an empty left child
where.setLeft(new Node<>(newItem, null, null));
else if (c > 0 && where.getLeft() == null) // base case - newItem > where.data, and there is an empty right child
where.setRight(new Node<>(newItem, null, null));
else if (c < 0) // recursively add to where's left subtree
add(newItem, where.getLeft());
else if (c > 0) // recursively add to where's right subtree
add(newItem, where.getLeft());
//duplicate
}
//Iterative add method
public void addNR(E newItem) {
Node<E> node = new Node<>(newItem);
if (root == null) {
root = node;
return;
}
Node<E> current = root;
Node<E> parent = null;
while (current != null) {
parent = current;
int c = newItem.compareTo(current.data);
if (c < 0)
current = current.getLeft();
else if (c > 0)
current = current.getLeft();
else{
//duplicate
}
}
int res = newItem.compareTo(parent.data);
if (res < 0)
parent.setLeft(node);
else
parent.setRight(node);
}
// Wrapper method for in-order traversal
public void inOrderTraversal() {
System.out.println("In-order traversal:");
inOrderTraversal(root);
}
// Performs an in-order traversal of the subtree rooted at where.
private void inOrderTraversal(Node<E> where) {
if (where != null) { // base case
inOrderTraversal(where.getLeft());
System.out.println(where.data);
inOrderTraversal(where.getLeft());
}
}
// Wrapper method for post-order traversal
public void postOrderTraversal() {
System.out.println("Post-order traversal:");
postOrderTraversal(root);
}
// Performs a post-order traversal of the subtree rooted at where.
private void postOrderTraversal(Node<E> where) {
if (where != null) { //base case
postOrderTraversal(where.getLeft());
postOrderTraversal(where.getLeft());
System.out.println(where.data);
}
}
// Wrapper method for find
public E find(E someItem) {
return find(someItem, root);
}
// Recursive find method. Searches the subtree rooted at where for someItem.
// Returns the item from the tree if found, or null if the item is not found.
private E find(E someItem, Node<E> where) {
if (where == null) // base case - item not found (think about this as searching an empty tree)
return null;
else {
int c = someItem.compareTo(where.data);
if (c == 0) // base case - item found!
return where.data;
else if (c < 0) // recursively search where's left subtree
return find(someItem, where.getLeft());
else // recursively search where's right subtree
return find(someItem, where.getLeft());
}
}
//Iterative find method
public E findNR(E someItem) {
Node<E> x = root;
while (x != null) {
int c = someItem.compareTo(x.data);
if(c < 0)
x = x.getLeft();
else if (c > 0)
x = x.getLeft();
else
return x.data;
}
return null;
}
// is the given key in the symbol table?
public boolean contains(E someItem) {
return findNR(someItem) != null;
}
// Wrapper method for toString
public String toString() {
return toString(root, "");
}
// Recursive toString. Computes the toString of the subtree rooted at where.
// The offset parameter keeps track of how much to indent each level of the tree.
private String toString(Node<E> where, String offset) {
if (where == null) // base case
return offset + "null";
else
// the toString starting from where is where.data, followed by
// the toString of where's left subtree, followed by
// the toString of where's right subtree
return offset + where.data + " " +
toString(where.getLeft(), offset + " ") + " " +
toString(where.getLeft(), offset + " ");
}
@SuppressWarnings("unchecked")
public Node<E> sortedArraytoBST(String[] list, int start, int end){
if (start > end)
return null;
int mid = (start + end) / 2;
Node<E> node = new Node<E>((E) list[mid]);
node.setLeft(sortedArraytoBST(list, start, mid-1));
node.setRight(sortedArraytoBST(list, mid + 1, end));
return node;
}
public static void main(String[] args) {
BinarySearchTree<String> stuff = new BinarySearchTree<>();
/*
stuff.add_book("George W. Bush");
stuff.add_book("George H. W. Bush");
stuff.add_book("Jeb Bush");
stuff.add_book("Laura Bush");
stuff.add_book("Barbara Bush");
stuff.add_book("JFK");
*/
stuff.addNR("George W. Bush");
stuff.addNR("George H. W. Bush");
stuff.addNR("Jeb Bush");
stuff.addNR("Laura Bush");
stuff.addNR("Barbara Bush");
stuff.addNR("JFK");
stuff.inOrderTraversal();
stuff.postOrderTraversal();
System.out.println();
System.out.println(stuff);
String[] stuffToFind = {"George W. Bush", "George H. W. Bush", "Jeb Bush", "Laura Bush", "Barbara Bush", "JFK", "James K. Polk", "Grover Cleveland", "Zachary Taylor", "William Harrison"};
for (String s : stuffToFind)
System.out.println("FIND" + stuff.find(s));
System.out.println("CONTAINS:");
System.out.println("George W. Bush: " + stuff.contains("George W. Bush"));
System.out.println("MLB: " + stuff.contains("MLB"));
System.out.println(stuff);
}
}
// no code for hashtable class yet; I need serious help on this also
ANY HELP WOULD BE APPRECIATED!
THANK YOU!!
In this project you will implement and explore the performance of different kinds of spell checkers. I have provided a text file containing about l 10,000 English words on eCourseware for you to use. You can assume that all words contain only lower-case letters. Approach i: Binary Search Tree One easy way of implementing a spell checker is to use a binary search tree. Given a list of valid words, you can insert them into a BST. Checking whether a word is spelled correctly simply involves searching the tree for that word. Ifthe word is found, great -if not, it must be misspelled! Remember that finding items in a BST takes O(log n) time on average, where n is the number of elements in the tree. Thus, the expected time cost of using this spell checker depends on the number of words that it's storing. 1. (14 pts) Write a BSTSpellChecker class. This class should have an instance variable of type Binarysearch TreeExplanation / Answer
Here is code Using Hashtable.
Before adding these files into your project, create one text file with name inputtext.txt , in this file add your inputs.
And one text file with name dictionary.txt , in this file all correct words that already you have.
For spellsuggest code you can add multiple words in wordprobabilityDatabase.txt file.
import java.io.*;
import java.util.*;
public class spellchecker{
Hashtable<String,String> dictionary; // To store all the words of the dictionary
boolean suggestWord ; // To indicate whether the word is spelled correctly or not.
public static void main(String [] args)
{
spellchecker checker = new spellchecker();
}
public spellchecker()
{
dictionary = new Hashtable<String,String>();
System.out.println("Welcome to the spell checker using Hashtable");
System.out.println("The spell checker would check every line from the input file and then give suggestions if needed after each line. ");
try
{
//Read and store the words of the dictionary
BufferedReader dictReader = new BufferedReader(new FileReader("dictionary.txt"));
while (dictReader.ready())
{
String dictInput = dictReader.readLine() ;
String [] dict = dictInput.split("\s");
for(int i = 0; i < dict.length;i++)
{
// key and value are identical
dictionary.put(dict[i], dict[i]);
}
}
dictReader.close();
String file = "inputtext.txt";
// Read and check the input from the text file
BufferedReader inputFile = new BufferedReader(new FileReader(file));
System.out.println("Reading from "+file);
// Initialising a spelling suggest object
spellingsuggest suggest = new spellingsuggest("wordprobabilityDatabase.txt");
// Reads input lines one by one
while ( inputFile.ready() )
{
String s = inputFile.readLine() ;
System.out.println (s);
String[] result = s.split("\s");
for (int x=0; x<result.length; x++)
{
suggestWord = true;
String outputWord = checkWord(result[x]);
if(suggestWord)
{
System.out.println("Suggestions for "+result[x]+" are: "+suggest.correct(outputWord)+" ");
}
}
}
inputFile.close();
}
catch (IOException e)
{
System.out.println("IOException Occured! ");
e.printStackTrace();
// System.exit(-1);
}
}
public String checkWord(String wordToCheck)
{
String wordCheck, unpunctWord;
String word = wordToCheck.toLowerCase();
// if word is found in dictionary then it is spelt correctly, so return as it is.
//note: inflections like "es","ing" provided in the dictionary itself.
if ((wordCheck = (String)dictionary.get(word)) != null)
{
suggestWord = false; // no need to ask for suggestion for a correct word.
return wordCheck;
}
// Removing punctuations at end of word and giving it a shot ("." or "." or "?!")
int length = word.length();
//Checking for the beginning of quotes(example: "she )
if (length > 1 && word.substring(0,1).equals("""))
{
unpunctWord = word.substring(1, length);
if ((wordCheck = (String)dictionary.get(unpunctWord)) != null)
{
suggestWord = false; // no need to ask for suggestion for a correct word.
return wordCheck ;
}
else // not found
return unpunctWord; // removing the punctuations and returning
}
// Checking if "." or ",",etc.. at the end is the problem(example: book. when book is present in the dictionary).
if( word.substring(length - 1).equals(".") || word.substring(length - 1).equals(",") || word.substring(length - 1).equals("!")
|| word.substring(length - 1).equals(";") || word.substring(length - 1).equals(":"))
{
unpunctWord = word.substring(0, length-1);
if ((wordCheck = (String)dictionary.get(unpunctWord)) != null)
{
suggestWord = false; // no need to ask for suggestion for a correct word.
return wordCheck ;
}
else
{
return unpunctWord; // removing the punctuations and returning
}
}
// Checking for "!"",etc ... in the problem (example: watch!" when watch is present in the dictionary)
if (length > 2 && word.substring(length-2).equals(","") || word.substring(length-2).equals("."")
|| word.substring(length-2).equals("?"") || word.substring(length-2).equals("!"") )
{
unpunctWord = word.substring(0, length-2);
if ((wordCheck = (String)dictionary.get(unpunctWord)) != null)
{
suggestWord = false; // no need to ask for suggestion for a correct word.
return wordCheck ;
}
else // not found
return unpunctWord; // removing the inflections and returning
}
// After all these checks too, word could not be corrected, hence it must be misspelt word. return and ask for suggestions
return word;
}
}
Code For Spelling Suggest.
import java.io.*;
import java.util.*;
import java.util.regex.*;
class spellingsuggest {
private final HashMap<String, Integer> DBWords = new HashMap<String, Integer>();
public spellingsuggest(String file) throws IOException
{
try
{
BufferedReader in = new BufferedReader(new FileReader(file));
Pattern p = Pattern.compile("\w+");
for(String temp = ""; temp != null; temp = in.readLine() ) // Reading the dictionary and updating the probabalistic values accordingly
{ // of the words according.
Matcher m = p.matcher(temp.toLowerCase());
while(m.find())
{
DBWords.put( (temp = m.group()), DBWords.containsKey(temp) ? DBWords.get(temp) + 1 : 1 ); // This will serve as an indicator to
} // probability of a word
}
in.close();
}
catch(IOException e)
{
System.out.println("Uh-Oh Exception occured!");
e.printStackTrace();
}
}
// Return an array containing all possible corrections to the word passed.
private final ArrayList<String> edits(String word)
{
ArrayList<String> result = new ArrayList<String>();
for(int i=0; i < word.length(); ++i)
{
result.add(word.substring(0, i) + word.substring(i+1));
}
for(int i=0; i < word.length()-1; ++i)
{
result.add(word.substring(0, i) + word.substring(i+1, i+2) + word.substring(i, i+1) + word.substring(i+2));
}
for(int i=0; i < word.length(); ++i)
{
for(char c='a'; c <= 'z'; ++c)
{
result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i+1));
}
}
for(int i=0; i <= word.length(); ++i)
{
for(char c='a'; c <= 'z'; ++c)
{
result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i));
}
}
return result;
}
public final String correct(String word)
{
if(DBWords.containsKey(word))
{
return word; // this is a perfectly safe word.
}
ArrayList<String> list_edits = edits(word);
HashMap<Integer, String> candidates = new HashMap<Integer, String>();
for(String s : list_edits) // Iterating through the list of all possible corrections to the word.
{
if(DBWords.containsKey(s))
{
candidates.put(DBWords.get(s),s);
}
}
// In the first stage of error correction, any of the possible corrections from the list_edits are found in our word database DBWords
// then we return the one verified correction with maximum probability.
if(candidates.size() > 0)
{
return candidates.get(Collections.max(candidates.keySet()));
}
// In the second stage we apply the first stage method on the possible collections of the list_edits.By the second stage statistics
// suggest we obtain an accuracy of about 98% !!
for(String s : list_edits)
{
for(String w : edits(s))
{
if(DBWords.containsKey(w))
{
candidates.put(DBWords.get(w),w);
}
}
}
return candidates.size() > 0 ? candidates.get(Collections.max(candidates.keySet())) : "Sorry but no possible corrections found!";
}
public static void main(String [] args) throws IOException
{
if(args.length > 0)
{
System.out.println((new spellingsuggest("wordprobabilityDatabase.txt")).correct(args[0]));
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.