In: Computer Science
Write a Java program that allows the user to specify a file name on the command line and prints the number of characters, words, lines, average number of words per line, and average number of characters per word in that file. If the user does not specify any file name, then prompt the user for the name.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileStats {
public static void main(String[] args) throws Exception {
String name = "";
if (args == null || args.length == 0) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter filename: ");
name = sc.next();
} else {
name = args[0];
}
File file = new File(name);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
// Initializing counters
int countWord = 0;
int lineCount = 0;
int charCount = 0;
// Reading line by line from the
// file until a null is returned
while ((line = reader.readLine()) != null) {
if (!(line.equals(""))) {
String[] wordList = line.split(" ");
lineCount++;
countWord += wordList.length;
charCount = charCount + line.length();
}
}
System.out.println("Line count: " + lineCount);
System.out.println("Word count: " + countWord);
System.out.println("Char count: " + charCount);
System.out.println("Avereage words per line: " + (countWord/(double)lineCount));
System.out.println("Avereage chars per wod: " + (charCount/(double)countWord));
reader.close();
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME