Jebathon
Jebathon

Reputation: 4581

Java - Scanner refuses to close?

I created a Program that takes a file(s) and outputs the number of lines, words and characters within that file respectively.

My issue is that when I compile the program it is 'stuck' and nothing is outputted on the interactions pane (or console).

The while loops should terminate and the new scanner objects should over-ride their old ones.

public static void main(String[] args) throws FileNotFoundException
{

    String[] filenames = new String[]{"cat.txt", "dog.txt", "mouse.txt", "horse.txt"} ;
    int totalLines = 0, totalWords = 0, totalCharacters = 0 ;

    for (String filename : filenames) 
    {
        int lines = 0, words = 0, characters = 0;

        try {

            Scanner scanner_lines = new Scanner (new File(filename)); //Reading Lines
            while (scanner_lines.hasNextLine()){
                lines++;
            }
            scanner_lines.close();

            Scanner scanner_words = new Scanner (new File(filename)); //Reading Words
            while (scanner_words.hasNext()){
                words++;
            }
            scanner_words.close();

            Scanner scanner_chars = new Scanner (new File(filename)); //Reading Characters
            scanner_chars.useDelimiter("");
            while (scanner_chars.hasNext()){
                characters++;
            }
            scanner_chars.close();
        } // end of try
        catch (FileNotFoundException e) {}

        System.out.println (lines + " " + words + " " + characters);

    }
}

Upvotes: 0

Views: 72

Answers (1)

Michael Easter
Michael Easter

Reputation: 24498

The loops need to consume the line, not just determine its existence:

Scanner scanner_lines = new Scanner (new File(filename)); //Reading Lines
while (scanner_lines.hasNextLine()){
    scanner_lines.nextLine();   // this is critical
    lines++;
}

Upvotes: 2

Related Questions