The task: Write a program that asks the user for a file and counts the number of characters, words, and lines in that file. Then the program asks for the name of the next file. When the user enters a file that doesn't exists, the program prints the total count of characters, words, and lines in all processed files and exits.
So far, when I run my code, my exception handling does not kick in if I try a random input name. When I input a correct file name, nothing happens.
My code:
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
/**
* A class to count the number of characters, words, and lines in files.
*/
public class FileCounter
{
/**
Constructs a FileCounter object.
*/
public FileCounter()
{
words = 0;
lines = 0;
}
/**
Processes an input source and adds its character, word, and line
counts to this counter.
@param in the scanner to process
*/
public void read(Scanner console) throws FileNotFoundException
{
String input = console.next();
FileReader reader = new FileReader(input);
Scanner in = new Scanner(reader);
}
/**
Gets the number of words in this counter.
@return the number of words
*/
public int getWordCount()
{
while (in.hasNextLine())
{
for(int i = 1; i <= in.nextLine().length(); i++)
{
int j = 0;
if (in.nextLine().substring(j, i).equals(" "));
words++;
j++;
}
}
return words;
}
/**
Gets the number of lines in this counter.
@return the number of lines
*/
public int getLineCount()
{
while (in.hasNextLine())
{
lines++;
}
return lines;
}
/**
Gets the number of characters in this counter.
@return the number of characters
*/
public int getCharacterCount()
{
//not worked on yet.
return 0;
}
private Scanner in;
private String input;
private int words;
private FileCounter counter;
private int lines;
}
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
/**
* This class prints a report on the contents of a number of files.
*
*/
public class FileAnalyzer
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
FileCounter counter = new FileCounter();
boolean more = true;
System.out.print("Please enter the file name: ");
while (more)
{
try
{
counter.read(in);
}
catch (FileNotFoundException exception)
{
System.out.println("Characters: " + counter.getCharacterCount());
System.out.println("Words: " + counter.getWordCount());
System.out.println("Lines: " + counter.getLineCount());
more = false;
}
}
}
}