Answer:
See explaination
Step-by-step explanation:
// LetterCount.java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class LetterCount {
public static void main(String[] args) {
// setting up a Scanner to read from keyboard
Scanner scanner = new Scanner(System.in);
try {
// asking and reading input file name
System.out.print("Enter name of input file: ");
String file = scanner.nextLine();
// reinitializing scanner to read from input file. this will throw
// file not found exception if file is not found.
scanner = new Scanner(new File(file));
// opening a file writer to create and write into output.txt file
PrintWriter writer = new PrintWriter(new File("output.txt"));
// creating a String containing all 26 alphabets
String alphabet = "abcdefghijklmnopqrstuvwxyz";
// creating an array containing 26 integers, all initialized to 0
int counts[] = new int[26];
// looping through the file
while (scanner.hasNext()) {
// reading next line, converting to lower case
String word = scanner.next().toLowerCase();
// looping through each character in current word
for (char c : word.toCharArray()) {
// finding index of c in alphabet
int index = alphabet.indexOf(c);
// if c is an alphabet, the index value will not be -1
if (index != -1) {
// incrementing counter at index position
counts[index]++;
}
}
}
// closing input file
scanner.close();
int largestCount = 0; // to store largest count of a character
String mostCommon = ""; // to store the character(s) that occur the
// most
// looping through counts array, finding the largest value
for (int i = 0; i < counts.length; i++) {
if (counts[i] > largestCount) {
// updating largestCount and mostCommon
largestCount = counts[i];
mostCommon = alphabet.charAt(i) + "";
} else if (counts[i] == largestCount) {
// same largest count, appending to mostCommon string
mostCommon += " " + alphabet.charAt(i);
}
}
// writing results to output file
writer.println("The most common letter(s): " + mostCommon);
writer.println("Count of occurrances: " + largestCount);
// closing file, saving changes, alerting user
writer.close();
System.out
.println("done! please check output.txt file for results.");
} catch (IOException e) {
// will be executed when the input/output file cant be opened or
// found, or if there is an error while reading the file
System.out.println(e.getMessage());
} catch (NoSuchElementException e) {
// will occur when there is no input provided for input file name.
System.out.println("No input!");
}
}
}