Write a program that prompts the user to enter a filename (use a Scanner to get the filename). The program then ouputs to the screen the number of lines, words, and characters in the file. Im having trouble counting the words
Here is my code:

import java.util.Scanner;
import java.io.*;

public class question1
{
    public static void main (String [] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter input filename: ");
        String filename = keyboard.nextLine();

        int counterChar = 0;
        int counterWords = 0;
        int counterLines = 0;

        Scanner fileOut = null;

        try
        {
            fileOut = new Scanner (new File(filename));

                while (fileOut.hasNextLine())
                    {
                    String line = fileOut.nextLine();
                    counterLines ++;

                    String [] words = line.split(" ");
                    counterWords = words.length;
                    counterWords ++;


                    for (int i= 0; i< line.length(); i++)
                        {
                        char c = line.charAt(i);
                        counterChar++;
                        }

                    }

            fileOut.close();
        }

        catch (FileNotFoundException exception)
        {
            System.out.println("could not find your file, sorry it didn't work out");
        }

        System.out.println(counterLines + " lines");
        System.out.println(counterWords+ " words");
        System.out.println(counterChar + " characters");    
    }

}

Im having trouble counting the words

Can you explain? How many words does the program read and how many does it count?
What is the output from the program.

its supposed to count 162 and its count 5 words :s

How many words were on the last line? 4 then add one = 5

Look at lines 28 & 29. How are they counting the words?
Explain what each of those two lines are doing.

I got it from my notes. I don't know how they are supposed to do it, but it counts words.

I don't know how they are supposed to do it

That's the problem that you need to figure out.

If you were going to add up a list of numbers, how would you do it?
words.length contains the number of words in the current line that needs to be added to the tota number of words. What java statement will add that to the total: counterWords?

For what? What is counterWords supposed to be used for?

counterwords is counting which lines words..first last or any other...?
because everytime when while loop is started it again initialized...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.