首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java中的拼写检查器,文件打开但无输出

Java中的拼写检查器,文件打开但无输出
EN

Stack Overflow用户
提问于 2018-07-25 15:34:21
回答 2查看 1.1K关注 0票数 2

我得到了拼写检查器的代码。它不读取words.txt文件。它只会打开对话框来选择文件。当我选择words.txt文件时,对话框关闭,没有任何反应。

我不确定这段代码出了什么问题。我一直在检查,似乎一切都很好。有人能告诉我哪里出错了吗?

谢谢。

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2018-07-25 16:12:21

代码语言:javascript
复制
 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是存储输出的文件

票数 0
EN

Stack Overflow用户

发布于 2019-03-15 03:02:05

代码语言:javascript
复制
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类:

代码语言:javascript
复制
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;
        }

    }
}       
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51513284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档