Java中的拼写检查程序,文件打开但没有输出

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (24)

我有一个拼写检查器的代码。它不会读取words.txt文件。它只打开对话框以选择文件。当我选择words.txt文件时,对话框关闭,没有任何反应。 我不确定这段代码有什么问题。我一直在检查它,一切似乎都到位了。有人能指出我出错的地方吗? 谢谢。

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
提问于
用户回答回答于
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类:

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;
        }

    }
}       
用户回答回答于
 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());
    }
}

其中tfLogFile是存储输出的文件

扫码关注云+社区

领取腾讯云代金券