Question
JAVA Code: Complete the program that reads from a text file and counts the occurrence of each letter of the English alphabet. The given code
JAVA Code:
Complete the program that reads from a text file and counts the occurrence of each letter of the English alphabet. The given code already opens a specified text file and reads in the text one line at a time to a temporary String. Your task is to go through that String and count the occurrence of the letters and then print out the final tally of each letter (i.e., how many 'a's?, how many 'b's?, etc.)
You can test your program with any text file; easiest if you put the text file in the same folder as your code. For example, if you have a file, book.txt, then you can simply type in book.txt when prompted by the program for the filename if the file is in the same folder as your program file.
Starter Code:
/* * program that reads in a text file and counts the frequency of each letter * displays the frequencies in descending order */
import java.util.*; //needed for Scanner import java.io.*; //needed for File related classes public class LetterCounter { public static void main(String args[]) throws IOException{ Scanner keyboard = new Scanner(System.in); //Scanner to read in file name System.out.println("Enter the name of the text file to read:"); String filename = keyboard.next(); //This String has all the letters of the alphabet //You can use it to "look up" a character using alphabet.indexOf(...) to see what letter it is //0 would indicate 'a', 1 for 'b', and so on. -1 would mean the character is not a letter String alphabet = "abcdefghijklmnopqrstuvwxyz"; //TODO: create a way to keep track of the letter counts //I recommend an array of 26 int values, one for each letter, so 0 would be for 'a', 1 for 'b', etc. Scanner fileScan = new Scanner(new File(filename)); //another Scanner to open and read the file //loop to read file line-by-line while (fileScan.hasNext()) { //this will continue to the end of the file String line = fileScan.nextLine(); //get the next line of text and store it in a temporary String line = line.toLowerCase( ); // convert to lowercase //TODO: count the letters in the current line
} fileScan.close(); //done with file reading...close the Scanner so the file is "closed" //print out frequencies System.out.println("Letters - Frequencies in file:"); //TODO: print out all the letter counts } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started