Question

In this lab you will write a spell check program. The program has two input files:...

In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the document to be spellchecked. The program will read in the words for the dictionary, then will read the document and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is or type in a replacement word and add the replacement word to the dictionary.

Dictionary

The Dictionary will have a field to hold the words; the type of this field will be an ArrayList of Strings.

Create the following interface and use it when implementing the Dictionary class.

   public interface DictionaryInterface {
      void addWord(String word);     //adds a new word to this dictionary
      boolean isWord(String word);   //returns true if word is in the dictionary and false otherwise
      int getSize();                 //number of words in the dictionary
      String toString();
   }

The toString() method should return a String containing all the words in the Dictionary, with each word on a separate line.

Create a constructor with one parm, a Scanner for the file containing the words for the dictionary. The constructor will read the words using the Scanner and store them in the Dictionary. Remember there is one word on each line of the dictionary file.

About Spellchecking

To spellcheck the file, your program will read each line of the document. It will compare every word in the input line with the words in the dictionary.

Words in the document will be separated by white space, and it is possible that there will be more than one whitespace character separating the words. Use the split method to access the individual words in the input file. Any white space or punctuation at the beginning or end of a word should be removed, and the lower case version of the word should be checked against the dictionary. More information on this is found below.

Before looking up a word in the dictionary it must be cleaned up: it must be converted to lowercase, and any punctuation mark at the end of the word (like . , ! or ?) must be removed. More information on this is found below.

After it is spellchecked, each word should be written to an output file called results.txt. Don't put each word on a separate line; the arrangement of words on a line should be the same in the document and in results.txt. The difference between the document and results.txt is that in results.txt each word is in lowercase and there is no punctuation. For example, suppose the document contains the following:

The Hunter Moon waxed round in the night sky, and put to
flight all the lesser stars. But low in the South one star shone red.

Then results.txt will contain:

the hunter moon waxed round in the night sky and put to
flight all the lesser stars but low in the south one star shone red

If a word is not found in the dictionary, the program will print a message indicating that the word was not found. Then it will ask the user whether to add the word to the dictionary, whether the word should be changed, or whether processing should continue with no change.

For example, suppose the text file contains the word "yikes", and "yikes" is not in the ditionary:

yikes not found in dictionary
   1 : replace in text file
   2 : add to dictionary
   3 : continue
   ==> 1
   enter word to replace yikes
   ==> yippee

[yippee will appear in results.txt instead of yikes
 yippee will be added to the dictionary if it is not already there]

yikes not found in dictionary
   1 : replace in text file
   2 : add to dictionary
   3 : continue
   ==> 2
   yikes added to dictionary

[yikes will appear in results.txt]

yikes not found in dictionary
   1 : replace in text file
   2 : add to dictionary
   3 : continue
   ==> 3

[yikes will appear in results.txt and the dictionary is unchanged]

In the first case, yikes will be replaced by yippee in the output file results.txt. In the second case yikes will appear in results.txt and it will be added to the dictionary.

The Spellcheck Class

The Dictionary is a field in the Spellcheck class.

Spellcheck will have a method to perform the spellchecking: read each line of the file, extract each word, clean it up (remove any punctuation at the end of the word), and see if it is in the dictionary. It also needs to handle the processing for words that are not found. Do not write one giant method to do all the spellchecking! Create some private methods that the spellcheck method will call to do parts of the processing.

Reading words from the input file: The spellcheck method will read a line from the input file and store it in a String. Each line will contain an unknown number of words, separated by one or more whitespace characters. To separate the words within the input line, we will use the split method in the String class. Look up the String class and read about the split method. You may not have heard of regular expressions, so don't worry if that part is confusing.

The split method (String[] split(String regex)) separates the items (called "tokens") in a String and stores them in an array of Strings. The tokens can be separated by whitespace, commas, slashes, or any other character(s). One of the parms to split specifies how to separate the tokens. In our input the tokens are words and they are separated by one or more whitespace characters. The value we will use to specify how to separate is "\\s+". Here is an explanation of "\\s+": '\s' represents any whitespace character. The extra \ indicates that '\s' represents one character, not the character '\' followed by the character 's'. The + means "one or more", so all together "\\s+" means "one or more whitespace character. When we call split with this parm, it returns an array of Strings where each element of the array is one word of this.

Cleaning up words before spellchecking: There is a String method that returns a lowercase version of a String. You can use other String and Character methods to check whether the last character of a word is a letter, and if not, create a String with that character removed.

Client Code

The main method will prompt for the name of the file containing the dictionary and the name of the input file to be spellchecked. Create the Scanner for the dictionary file and pass it to the Dictionary constructor. Create the Scanner for the input file, perform the spellcheck, and write out the updated dictionary.

Use exception handling in the main method to ensure the input files were found and opened properly. If not handle the situation by prompting the user again for the correct file name.

Do not use any set or get methods.

  • If user chooses to change the word, then the user will be prompted for the new word and the new word will replace the original word in results.txt. If the new word is not in the dictionary, it will be added to the dictionary.
  • If the user chooses to add the word to the dictionary, the word is added to the dictionary and it is not changed in results.txt.
  • If the user chooses to continue, no change is made. The word is unchanged and the dictionary is unchanged.

The code need to be in JAVA thank you

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have implemented all the things. Please read the code carefully and if you have any questions leave a comment.

Files used:

1. dictionary.txt

2. wordsToCheck.txt

3. DictionaryInterface.java

4. Dictionary.java

5. SpellChecker.java

////////////////////////////////////dictionary.txt//////////////////////

Aalesund
AAP
AAPSS
Aaqbiye
Aar
Aara
Aarau
AARC
aardvark
aardvarks
aardwolf
aardwolves
Aaren
Aargau
aargh
Aarhus
Aarika
Aaron
Aaronic
Aaronical
Aaronite
AARP
aarrgh
aarrghh
Aaru
AAS
abaisance
abaised
abaiser
abaisse
abaissed
abaka
Abakan
abakas
Abakumov
abalation
abalone
abalones
all
and
around
bechanced
bechances
bechancing
becharm
becharmed
becharming
becharms
bechase
becher
bechern
Bechet
bechic
bechignoned
bechirp
Bechler
Becht
Bechtel
Bechtelsville
Bechtler
Bechuana
Bechuanaland
Bechuanas
becircled
becivet
Beck
Becka
becked
beckelite
Beckemeyer
Becker
Beckerman
Becket
beckets
but
flight
Hunter
in
lesser
Moon
night
overdaring
overdash
overdated
overdazed
overdaz
put
round
red  
semistock
semistory
sky
success
sweet
semita
semitact
semitae
semital
semitaur
Semite
south
star
shone
the
to
triduam
triduan
triduo
triduum
Waxed
Zuni
Zunian
zunyite
zunis
Zupus
Zwart
ZWEI
Zweig
Zwick
Zwickau

//////////////////////////////////////////////End Dictionary.txt//////////////////////////////////

///////////////////////////////////////////////WordsToCheck.txt///////////////////////////////////

The Hunter Moon waxed round in the night sky, and put to
flight all the lesser stars. But low in the South one star shone red.

///////////////////////////////////ENd WordTocheck.txt

///////////////////////////////////////////DictionaryInterface.java///////////////

package com.java.spellchecker;

public interface DictionaryInterface {
   void addWord(String word); // adds a new word to this dictionary

   boolean isWord(String word); // returns true if word is in the dictionary and false otherwise

   int getSize(); // number of words in the dictionary

   String toString();
}

////////////////////////////End DictionaryInterfacce.java/////////////////

/////////////////////////////////Dictionary.java//////////////////

package com.java.spellchecker;

import java.util.ArrayList;
import java.util.Scanner;

//A class that implements all the methods of DictionaryInterface
public class Dictionary implements DictionaryInterface {

   private ArrayList<String> words = new ArrayList<>();

   @Override
   public void addWord(String word) {
       this.words.add(word);
   }

   @Override
   public boolean isWord(String word) {
       if (words.stream().anyMatch(word::equalsIgnoreCase)) {
           return true;
       }
       return false;
   }

   @Override
   public int getSize() {
       return words.size();
   }

   @Override
   public String toString() {
       String ans = "";
       for (int i = 0; i < words.size(); i++) {
           ans += words.get(i) + " ";
       }
       return ans;
   }

   // One arg constructor that takes the file Name of the dictionary file to create
   // a list of Strings
   public Dictionary(Scanner sc) {
       while (sc.hasNext()) {
           String str = sc.nextLine();
           words.add(str);
       }
       sc.close();

   }
}
////////////////////////////End Dictionary.java///////////////////////

/////////////////////////////SpellChecker.java////////////////////

package com.java.spellchecker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class SpellChecker {

   // fileName to store results
   private static String resultFileName = "C:\EclipseWorkspace\src\com\java\spellchecker\results.txt";
   // variable storing fileName for dictionary file
   private static String dictionaryFileName;
   // variable storing fileName for document to spell check
   private static String fileToSpellCheck;
   // instance variable for dictionary class
   private static Dictionary dictionary;
   // Scanner to read file
   private static Scanner fileScanner;
   // scanner to get user input
   private static Scanner consoleScanner;

   public static void main(String args[]) {
       consoleScanner = new Scanner(System.in);
       System.out.println("Please enter a full Path of the file containing Dictionary");
       // Get dictionary file name from user
       dictionaryFileName = consoleScanner.next();

       try {
           fileScanner = new Scanner(new File(dictionaryFileName));
           dictionary = new Dictionary(fileScanner);
           spellCheck();
       } catch (FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }

   // The method takes file name for check we need to do spell Check and try to
   // find each var in dictioary
   private static void spellCheck() {
       try {

           System.out.println("Please enter a full Path of the input file to be spellchecked");
           // get file name from user
           fileToSpellCheck = consoleScanner.next();
           fileScanner = new Scanner(new File(fileToSpellCheck));
           while (fileScanner.hasNext()) {
               // Each word must be converted to lowercase, and any punctuation mark at the end
               // of the word must be removed.
               String strArr[] = fileScanner.nextLine().replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\s+");
               for (int i = 0; i < strArr.length; i++) {
                   String str = strArr[i];
                   // check if the word is in the dictionary or not
                   boolean isWord = dictionary.isWord(str);
                   // if the word is not in dictionary then give option to user about what to do
                   if (!isWord) {
                       System.out.println("Word " + str + " not found in the dictionary.");
                       System.out.println("1 : replace in text file " + "2 : add to dictionary " + "3 : continue");

                       int input = consoleScanner.nextInt();
                       consoleScanner.nextLine();
                       str = processTheWord(str, input);
                   }
                   writeToFile(str, resultFileName);
               }
               writeToFile(" ", resultFileName);
           }

           fileScanner.close();
       } catch (FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }

   }

   // If a word is not found in the dictionary, the program will print a message
   // indicating that the word was not found. Then it will ask the user whether 1.
   // to
   // add the word to the dictionary, 2. whether the word should be changed, or
   // 3. whether processing should continue with no change.
   private static String processTheWord(String str, int input) {
       String wordToAdd = str;
       switch (input) {
       case 1:
           wordToAdd = replaceWord(str);
           break;
       case 2:
           dictionary.addWord(str);
           wordToAdd = str;
           writeToFile(wordToAdd, dictionaryFileName);
           System.out.println(wordToAdd + " added to dictionary");
           System.out.println("[" + str + " will appear in results.txt]");
           break;
       case 3:
           wordToAdd = str;
           System.out.println("[" + str + " will appear in results.txt and the dictionary is unchanged]");
           break;
       default:
           break;
       }
       return wordToAdd;
   }

   // Write word to File could be adding a new word to dictionary or To the result
   // file
   private static void writeToFile(String wordToAdd, String fileName) {
       BufferedWriter writer;
       try {
           writer = new BufferedWriter(new FileWriter(fileName, true));
           if (fileName.equals(dictionaryFileName)) {
               writer.write(wordToAdd + " ");
           } else {
               writer.write(wordToAdd + " ");
           }

           writer.close();
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }

   }

   // If user wants to replce the word in the result.txt file. And if the new word
   // is not in dictionary add it to dictionary as well
   private static String replaceWord(String str) {
       System.out.println("enter word to replace " + str);
       String newWord = consoleScanner.nextLine();
       System.out.println("[" + newWord + " will appear in results.txt instead of " + str + " " + newWord
               + " will be added to the dictionary if it is not already there]");

       if (!dictionary.isWord(newWord)) {
           dictionary.addWord(newWord);
           writeToFile(newWord, dictionaryFileName);
       }
       return newWord;
   }
}

///////////////////////////////End SpellChecker.java///////////////////////

Output screenshot

Add a comment
Know the answer?
Add Answer to:
In this lab you will write a spell check program. The program has two input files:...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Dictionary.java DictionaryInterface.java Spell.java SpellCheck.java In this lab you will write a spell check program. The program...

    Dictionary.java DictionaryInterface.java Spell.java SpellCheck.java In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the input file to be spell checked. The program will read in the words for the dictionary, then will read the input file and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is, add...

  • Write a spell checker that stores a set of words, W, in a hash table and...

    Write a spell checker that stores a set of words, W, in a hash table and implements a function, spellCheck(s), which performs a spell check on the string s with respect to the set of words, W. If s is in W, then the call to spellCheck(s) returns an iterable collection that contains only s, because it is assumed to be spelled correctly in this case. Otherwise, if s is not in W, then the call to spellCheck(s) returns a...

  • For this lab you will write a Java program that plays a simple Guess The Word...

    For this lab you will write a Java program that plays a simple Guess The Word game. The program will prompt the user to enter the name of a file containing a list of words. These words mustbe stored in an ArrayList, and the program will not know how many words are in the file before it starts putting them in the list. When all of the words have been read from the file, the program randomly chooses one word...

  • For this assignment, you will use your knowledge of arrays and ArrayLists to write a Java...

    For this assignment, you will use your knowledge of arrays and ArrayLists to write a Java program that will input a file of sentences and output a report showing the tokens and shingles (defined below) for each sentence. Templates are provided below for implementing the program as two separate files: a test driver class containing the main() method, and a sentence utilities class that computes the tokens and shingles, and reports their values. The test driver template already implements accepting...

  • In python Count the frequency of each word in a text file. Let the user choose...

    In python Count the frequency of each word in a text file. Let the user choose a filename to read. 1. The program will count the frequency with which each word appears in the text. 2. Words which are the spelled the same but differ by case will be combined. 3. Punctuation should be removed 4. If the file does not exist, use a ‘try-execption’ block to handle the error 5. Output will list the words alphabetically, with the word...

  • Capitalization JAVA In this program, you will read a file line-by-line. For each line of data...

    Capitalization JAVA In this program, you will read a file line-by-line. For each line of data (a string), you will process the words (or tokens) of that line one at a time. Your program will capitalize each word and print them to the screen separated by a single space. You will then print a single linefeed (i.e., newline character) after processing each line – thus your program will maintain the same line breaks as the input file. Your program should...

  • For this week's lab, you will use two of the classes in the Java Collection Framework:...

    For this week's lab, you will use two of the classes in the Java Collection Framework: HashSet and TreeSet. You will use these classes to implement a spell checker. Set Methods For this lab, you will need to use some of the methods that are defined in the Set interface. Recall that if set is a Set, then the following methods are defined: set.size() -- Returns the number of items in the set. set.add(item) -- Adds the item to the...

  • For this week's lab, you will use two of the classes in the Java Collection Framework:...

    For this week's lab, you will use two of the classes in the Java Collection Framework: HashSet and TreeSet. You will use these classes to implement a spell checker. Set Methods For this lab, you will need to use some of the methods that are defined in the Set interface. Recall that if set is a Set, then the following methods are defined: set.size() -- Returns the number of items in the set. set.add(item) -- Adds the item to the...

  • FOR JAVA Write a program that takes two command line arguments: an input file and an...

    FOR JAVA Write a program that takes two command line arguments: an input file and an output file. The program should read the input file and replace the last letter of each word with a * character and write the result to the output file. The program should maintain the input file's line separators. The program should catch all possible checked exceptions and display an informative message. Notes: This program can be written in a single main method Remember that...

  • Python 3.7 Coding assignment This Program should first tell users that this is a word analysis...

    Python 3.7 Coding assignment This Program should first tell users that this is a word analysis software. For any user-given text file, the program will read, analyze, and write each word with the line numbers where the word is found in an output file. A word may appear in multiple lines. A word shows more than once at a line, the line number will be only recorded one time. Ask a user to enter the name of a text file....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT