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");
}
}