In: Computer Science
code a Java program that:
Requests from the user for a text filename to read the text inside, then it calculates the frequency of each letter contained in the file. When punctuation is ignored, there is no need to distinguish between upper and lower case. The text file should be named as “input” with only letters inside. For example,
a 11
c 9
e 16
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileFrequency {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a file name: ");
File file = new File(in.nextLine()); // read a file and create a file.
try {
Scanner fin = new Scanner(file); // create a scanner to read from file
int[] counts = new int[26];
char ch;
String line;
while (fin.hasNextLine()) { // read each line from file
line = fin.nextLine();
for (int i = 0; i < line.length(); i++) {
ch = Character.toLowerCase(line.charAt(i));
if (Character.isAlphabetic(ch)) {
counts[ch-'a']++;
}
}
}
for (int i = 0; i < counts.length; i++) {
ch = (char) ('a' + i);
System.out.println(ch + " " + counts[i]);
}
fin.close(); // close file.
} catch (FileNotFoundException e) {
System.out.println("Error. " + file.getAbsolutePath() + " does not exists!"); // if file does not exist, report an error
}
}
}