mercredi 28 octobre 2015

Word counter program not producing correct number of words

I'm new to reading text from a file. I've got a task for which I need to print the amount of words which are in a file.

I'm using TextEdit on mac OS which ends in .rtf

When I run the following program, I get the output 5 even when the document is empty. When I add words, the count doesn't increment correctly.

Thanks.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Analyze{ 


public static void main(String[] args) throws FileNotFoundException{
    Scanner console = new Scanner(System.in);
    int words = 0; 
    System.out.println("This is a word counter");
    System.out.println("File name");
    String filename = console.next();
    File name = new File(filename);

    Scanner int2 = new Scanner(name);

    while (int2.hasNext()) {
        String temp = int2.next();
        words++;
    }

    System.out.println(words);
    }
}

Aucun commentaire:

Enregistrer un commentaire