0

我正在为一个程序编写代码,该程序从文本文件中获取单词并将它们按字母顺序排列,但我似乎无法让扫描仪工作?

public static void Option1Method() throws IOException {
    FileWriter aFileWriter = new FileWriter("wordlist.txt", true);
    PrintWriter out = new PrintWriter(aFileWriter);
    String word = JOptionPane.showInputDialog(null, "Enter a word");

    out.println(word);
    out.close();

    aFileWriter.close();

    String inputFile = "wordlist.txt";
    String outputFile = "wordlist.txt";
    FileReader fileReader = new FileReader(inputFile);
    Scanner scan = new Scanner(fileReader);
    scan.nextLine;
    String inputLine;
    List<String> lineList = new ArrayList<String>();
    while ((inputLine = scan.nextLine()) != null) {
        lineList.add(inputLine);
    }
    fileReader.close();

    Collections.sort(lineList);

    FileWriter fileWriter = new FileWriter(outputFile);
    PrintWriter out1 = new PrintWriter(fileWriter);
    for (String outputLine : lineList) {
        out1.println(outputLine);
    }
    out1.flush();
    out1.close();
    fileWriter.close();
}
4

1 回答 1

4

Scanner#nextLine是一种方法。您需要添加括号。代替

scan.nextLine;

scan.nextLine();
             ^

Scanner用于hasNextLine检查后续行。调用scan.nextLine()打开的文件最终会导致NoSuchElementException. 代替:

while ((inputLine = scan.nextLine()) != null) {
  ...
}

while (scan.hasNextLine()) {
   inputLine = scan.nextLine();
   lineList.add(inputLine);
}

请注意,第一次调用会scan.nextLine()导致第一行被使用,而不被写入排序的输出文件。如果您打算将所有单词写入文件,请删除或注释此行。

于 2013-04-06T18:01:00.343 回答