Question

JAVA Code: Complete the program that reads from a text file and counts the occurrence of...

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
  
  
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Code to copy

/*
* 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";
int count [] = new int[26];
char mych [] = new char[26];
for(int i=0;i<26;i++)
mych[i]=(char)(i+97);
//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
for(int i=0;i<line.length();i++)
{
if(line.charAt(i)>=97 && line.charAt(i)<=122)
count[line.charAt(i)-97]+=1;
}
}
fileScan.close(); //done with file reading...close the Scanner so the file is "closed"

//print out frequencies
System.out.println("Letters - Frequencies in file:");
int temp;
char temp1;
//sorting
for (int i = 0; i < ( 26 - 1 ); i++)
{
for (int j = 0; j < 26 - i - 1; j++)
{
if (count[j] < count[j+1])
{
temp = count[j];
temp1=mych[j];
count[j] = count[j+1];
mych[j]=mych[j+1];
count[j+1] = temp;
mych[j+1]=temp1;
}
}
}
for(int i=0;i<26;i++)
{
System.out.println("Frequency of letter '"+(char)mych[i]+"' in file is: "+count[i]);
}


}
}

//Sample output

C:\Windows system32\cmd.exe UsersIndrajeet Meena Desktop>javac LetterCounter.java :\Users\Indrajeet Meena\Desktop>Java LetterCounter nter the name of the text file to read: input.txt etters Frequencies in file: requency of lettertin file is: 5 requency of letterein file is: 4 requency of letterin file is: 4 requency of letterr in file is: 3 requency of letterj in file is: 2 requency of letterw in file is: 2 requency of lettera in file is: 1 requency of letterf in file is: 1 requency of letterk in file is: 1 requency of letternin file is: 1 requency of lettery in file is: 1 requency of letterb in file is: 0 requency of lettercin file is: 0 requency of letterd in file is: 0 requency of letterg in file is: 0 requency of letterh in file is: 0 requency of letteri in file is: 0 requency of letter1 in file is: 0 requency of letterin file is: 0 requency of lettero in file is: 0 requency of letterp in file is: 0 requency of lettersin file is: 0 requency of letterin file is: 0 requency of letterin file is: 0 requency of letterx in file is: 0 requency of letterz in file is: 0 UsersIndrajeet Meena Desktop>

//Input file

Add a comment
Know the answer?
Add Answer to:
JAVA Code: Complete the program that reads from a text file and counts the occurrence of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • Write a C++ program that reads text from a file and encrypts the file by adding...

    Write a C++ program that reads text from a file and encrypts the file by adding 6 to the ASCII value of each character. See section 5.11 in Starting out with C++ for information on reading and writing to text files. Your program should: 1. Read the provided plain.txt file one line at a time. Because this file has spaces, use getline (see section 3.8). 2. Change each character of the string by adding 6 to it. 3. Write the...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • Homework Assignment on Mimir: Read in a file "numbers.txt" into a Java program. Sum up all...

    Homework Assignment on Mimir: Read in a file "numbers.txt" into a Java program. Sum up all the even numbers over 50. Print the result to the console using System.out.println(); The file will only have numbers. Code: import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; /** * * @author David */ public class ReadingFiles {     /**      * @param args the command line arguments      */     public static void main(String[] args) throws FileNotFoundException {         // TODO code application logic here...

  • I need eclipse code for : Write a program that analyzes text written in the console...

    I need eclipse code for : Write a program that analyzes text written in the console by counting the number of times each of the 26 letters in the alphabet occurs. Uppercase and lowercase letters should be counted together (for example, both ‘A’ and ‘a’ should count as an A). Any characters that are not letters should be ignored. You must prompt the user to enter the text to be analyzed. Then, for any letter that appeared at least once...

  • Write a complete C program that inputs a paragraph of text and prints out each unique...

    Write a complete C program that inputs a paragraph of text and prints out each unique letter found in the text along with the number of times it occurred. A sample run of the program is given below. You should input your text from a data file specified on the command line. Your output should be formatted and presented exactly like the sample run (i.e. alphabetized with the exact spacings and output labels). The name of your data file along...

  • import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads...

    import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads numbers from a file, calculates the mean and standard deviation, and writes the results to a file. */ public class StatsDemo { // TASK #1 Add the throws clause public static void main(String[] args) { double sum = 0; // The sum of the numbers int count = 0; // The number of numbers added double mean = 0; // The average of the...

  • In Python 3, Write a program that reads in a text file that consists of some...

    In Python 3, Write a program that reads in a text file that consists of some standard English text. Your program should count the number of occurrences of each letter of the alphabet, and display each letter with its count, in the order of increasing count. What are the six most frequently used letters?

  • Write a C program that reads characters from a text file, and recognizes the identifiers in...

    Write a C program that reads characters from a text file, and recognizes the identifiers in the text file. It ignores the rest of the characters. An identifier is a sequence of letters, digits, and underscore characters, where the first character is always a letter or an underscore character. Lower and upper case characters can be part of the identifier. The recognized identifier are copied into the output text. b. Change the C program in exercise 2, so that all...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT