2

I got this code for a spell Checker. It doesn't read the words.txt file. It only opens the dialog box to choose a file. When I choose the words.txt file, the dialog box closes and nothing happens.
I am not sure what is wrong with this code. I keep checking it, and everything seems in place. Can someone point me where I am going wrong please?
Thank you.

import java.io.*;
import java.util.Scanner;
import java.util.HashSet;
import javax.swing.*;
import java.util.TreeSet;

/**
 * This class works as a basic spell-checker. It uses the file words.txt to
 * check whether a given word is correctly spelled.
 */
public class SpellChecker {

    public static void main(String[] args) {

        Scanner words;
        HashSet<String> dict = new HashSet<String>();
        Scanner userFile;

        try {

            words = new Scanner(new File("src/words.txt"));

            while (words.hasNext()) {
                String word = words.next();
                dict.add(word.toLowerCase());
            }

            userFile = new Scanner(getInputFileNameFromUser());

            // Skip over any non-letter characters in the file.
            userFile.useDelimiter("[^a-zA-Z]+");

            HashSet<String> badWords = new HashSet<String>();
            while (userFile.hasNext()) {
                String userWord = userFile.next();
                userWord = userWord.toLowerCase();
                if (!dict.contains(userWord) && 
                    !badWords.contains(userWord)) {

                    badWords.add(userWord);
                    TreeSet<String> goodWords = new TreeSet<String>();
                    goodWords = corrections(userWord, dict);
                    System.out.print(userWord + ": ");
                    if (goodWords.isEmpty())
                        System.out.println("(no suggestions)");
                    else {
                        int count = 0;
                        for (String goodWord: goodWords) {
                            System.out.print(goodWord);
                            if (count < goodWords.size() - 1)
                                System.out.print(", ");
                            else
                                System.out.print("\n");
                            count++;
                        }
                    }

                }

            }

        }
        catch (FileNotFoundException e) {
            System.exit(0);
        }

    } // end main()

    /**
     * Lets the user select an input file using a standard file selection
     * dialog box. If the user cancels the dialog without selecting a file,
     * the return value is null.
     *
     * @return A file selected by the user, if any. Otherwise, null.
     */
    static File getInputFileNameFromUser() {

        JFileChooser fileDialog = new JFileChooser();
        fileDialog.setDialogTitle("Select File for Input");
        int option = fileDialog.showOpenDialog(null);
        if (option != JFileChooser.APPROVE_OPTION)
            return null;
        else
            return fileDialog.getSelectedFile();

    } // end getInputFileNameFromUser()

    /*
     * Gives a list of possible correct spellings for misspelled words which
     * are variations of a a given word that are present in the dictionary.
     *
     * @return A tree set containing a list of possible corrections to the
     *         misspelled word.
     */
    static TreeSet<String> corrections(String badWord, HashSet<String> dictionary) {

        TreeSet<String> possibleWords =  new TreeSet<String>();
        String subStr1, subStr2, possibility;

        for (int i = 0; i < badWord.length(); i++) {

            // Remove character i from the word.
            subStr1 = badWord.substring(0, i);
            subStr2 = badWord.substring(i + 1);

            // Delete any one of the letters from the misspelled word.
            possibility = subStr1 + subStr2;
            if (dictionary.contains(possibility))
                possibleWords.add(possibility);

            // Change any letter in the misspelled word into any other
            // letter.    
            for (char ch = 'a'; ch <= 'z'; ch++) {
                possibility = subStr1 + ch + subStr2;
                if (dictionary.contains(possibility))
                    possibleWords.add(possibility);
            }

            // Divide the word into two substrings.
            subStr1 = badWord.substring(0, i);
            subStr2 = badWord.substring(i);

            // Insert any letter at any point in the misspelled word.
            for (char ch = 'a'; ch <= 'z'; ch++) {
                possibility = subStr1 + ch + subStr2;
                if (dictionary.contains(possibility))
                    possibleWords.add(possibility);
            }

            // Insert a space at any point in the misspelled word and check
            // that both of the words that are produced are in the dictionary.
            char ch = ' ';
            possibility = subStr1 + ch + subStr2;
            if (dictionary.contains(subStr1) && dictionary.contains(subStr2))
                      possibleWords.add(possibility);

        }

        // Swap any two neighbouring characters in the misspelled word.
        for (int i = 1; i < badWord.length(); i++) {
            subStr1 = badWord.substring(0, i - 1);
            char ch1 = badWord.charAt(i - 1);
            char ch2 = badWord.charAt(i);
            subStr2 = badWord.substring(i + 1);
            possibility = subStr1 + ch2 + ch1 + subStr2;
            if (dictionary.contains(possibility))
                possibleWords.add(possibility);
        }

        return possibleWords;

    } // end corrections()

} // end class SpellChecker
Lila
  • 21
  • 4

2 Answers2

0
 private void getInputFileNameFromUser(java.awt.event.ActionEvent evt) {
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "Text Files", "txt");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
        tfLogFile.setText(chooser.getSelectedFile().getPath());
    }
}

where the tfLogFile is the file to store the output

bbadawee
  • 120
  • 11
  • How do I set up tfLogFile though? If I insert your code instead of mine, I get an error that tfLogFile cannot be resolved. When I read your code it seems that it does about the same thing than mine. I don't get what's different? – Lila Jul 25 '18 at 08:50
  • i've tested your code and it's working fine the problem is with the file path, make sure to add the exact path, or just debug it and show us the results so we can see what's really going wrong – bbadawee Jul 25 '18 at 09:52
  • I changed the file path, I put the exact path instead. But when I run my program, all it does is showing up the dialog box (so i guess it's not going through my words.txt file) and then i choose my words.txt file, and that's it. the program ends with no output. The debugger only gets: /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home/bin/java (Jul 25, 2018, 12:03:42 PM) – Lila Jul 25 '18 at 19:04
0
import java.util.*;

public class Word implements Comparable<Word> {

    private String word;
    private ArrayList<Integer> lines;

    public Word() {
        lines = new ArrayList<>();
    }

    public Word(String w, int lineNumber) {
        word = w;
        lines = new ArrayList<>();
        lines.add(lineNumber);
    }

    public String getWord() {
        return word;
    }

    public ArrayList<Integer> getLines() {
        return lines;
    }

    public void addLine(int lineNumber) {
        lines.add(lineNumber);
    }

    public String toString() {
        return word + " : "+lines.toString();
    }

    public boolean equals(Object w) {
        return this.word.equals(((Word)w).word);
    }

    public int compareTo(Word w) {
        return this.word.compareTo(w.word);
    }

}

SpellChekker class:

import java.util.*;
import java.io.*;

public class SpellChecker implements SpellCheckInterface {


    LinkedList<String> dict;
    LinkedList<Word> misspelled;

    public SpellChecker() {
        dict = new LinkedList<>();
        misspelled = new LinkedList<Word>();
    }

     /**
     * Loads the dictionary contained in the specified file
     * 
     * @param filename The name of the dictionary file to be loaded
     * @return true If the file was successfully loaded, false
     *          if the file could not be loaded or was invalid
     * @throws IOException if filename does not exist
     */
    @Override
    public boolean loadDictionary(String fileName) throws  IOException {
        try {
            File infile = new File(fileName);
            try (Scanner in = new Scanner(infile);){
                while (in.hasNext()) {
                    dict.add(in.next());
                }
            }
        } catch(Exception ex) {
            System.out.println(ex);
            return false;
        }

        return true;
    }

     /**
     * Check the document for misspelled words
     *
     * @return A list of misspelled words and
     *         the line numbers where they occur.
     * @throws @throws IOException if filename does not exist
     */
    @Override
    public boolean checkDocument(String fileName) throws IOException {
        misspelled = new LinkedList<>();
        int lineNumber = 0;
        try {
            File infile = new File(fileName);
            System.out.println("\n\nFile Name:"+ fileName);
            try ( Scanner in = new Scanner(infile); ){

                while (in.hasNextLine()){

                   String line = in.nextLine().toLowerCase();
                   lineNumber++;
                   String[] tokens = line.split("\\P{Alpha}+");
                   for(int i=0;i<tokens.length;++i) {
                    if (tokens[i].length()==0) continue;
                    if(!dict.contains(tokens[i])) {
                      Word word = new Word(tokens[i],lineNumber);
                       if(misspelled.contains(word)) {
                        int index = misspelled.indexOf(word);
                        misspelled.get(index).addLine(lineNumber);
                       }
                       else
                        misspelled.add(word);
                     }  
                      }
                }

            }
        } catch (IOException ex) {
            System.out.println(ex);
            return false;
        }

        Object[] list = misspelled.toArray();
        Arrays.sort(list);

        if(list.length==0){
            return true;
        }else {
            System.out.println("Misspelled words are");
            for(Object w : list){
                System.out.println(w);
            }
            return false;
        }

    }
}       
Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
garagol
  • 15
  • 5