I am writing code that counts the number of characters, words and lines in a .txt file. My sample text file has 21 words, 2 lines, and 114 characters. My program output states there are 21 words, 2 lines and 113 characters. The file is mostly barren and is only meant for testing purposes. In the file is:
This is a test for counter function. Contents are subject to change.
This line tests if the line count is correct.
My program is:
public static void counter(){
String file_name = "input.txt";
File input_file = new File(file_name);
Scanner in_file = null;
int word_count = 0;
int line_count = 0;
int char_count = 0;
String line;
try{
in_file = new Scanner(input_file);
}
catch(FileNotFoundException ex){
System.out.println("Error: This file doesn't exist");
System.exit(0);
}
try{
while(in_file.hasNextLine()){
line = in_file.nextLine();
char_count = char_count + line.length();
String[] word_list = line.split(" ");
word_count = word_count + word_list.length;
String[] line_list = line.split("[,\\n]");
line_count = line_count + line_list.length;
}
}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Error: The file format is incorrect");
}
catch(InputMismatchException ex){
System.out.println("Error: The file format is incorrect");
}
finally{
System.out.print("Number of words: ");
System.out.println(word_count);
System.out.print("Number of lines: ");
System.out.println(line_count);
System.out.print("Number of characters: ");
System.out.println(char_count);
in_file.close();
}
}
The correct code for this would be
public void calculateFileCharecteristics(String fileName){
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(filename)))){
String line;
int lineCount = 0;
int totalCharCount = 0;
while((line=bufferedReader.readLine())!=null){
lineCount++;
int charCount = line.split("\n").length;
totalCharCount +=charCount;
}
}
}