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.


import java.util.Scanner;

public class Analyze{ 

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

    Scanner int2 = new Scanner(name);

    while (int2.hasNext()) {
        String temp =;


Aucun commentaire:

Enregistrer un commentaire