Question

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();
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top