I'm writing code for a program which takes in words from a text file and arranges them into alphabetical order, but I can't seem to get the scanner working?

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();
}
有帮助吗?

解决方案

Scanner#nextLine is a method. You need to add parenthesis. Replace

scan.nextLine;

with

scan.nextLine();
             ^

Also Scanner uses hasNextLine to check for subsequent lines. Calling scan.nextLine() on an open file will eventually cause a NoSuchElementException. Replace:

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

with

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

Note that the first call to scan.nextLine() causes the first line to be consumed without being written to the sorted output file. Remove or comment this line if you intend all words to be written to file.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top