Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Compute the frequencies of characters in a given input file in java (Ignore all

ID: 3742869 • Letter: C

Question

Compute the frequencies of characters in a given input file in java

(Ignore all tabs, spaces and line returns)

I. Input: a txt file (use argv[])   

II. Output: a txt file (use argv[]) with the following format:

(Do not print any chars that have zero count.)

  

      char1 # count

      char2 # count

III. Data structure:

      - charIn (char)

      - index

      - charCounts[256] a 1D array where 256 is max number of different ascii characters

   - printArray

VI. Algorithm for counting

step 0: - open input and output files

         - initialize charCounts array to zero.

        

step 1: charIn <- get the next character from inFile, one character at a time

step 2: index <- cast charIn to integer

step 3: charCounts[index]++

step 4: repeat step 1 to step 3 while infile is not empty

step 5: printArray

step 6: close all files

VII. Algorithm for printArray

step 1: index <--0

step 2: if charCounts[index] > 0

           symbol <-- cast index to charactor

           write symbol charCounts[index] per text line

step 3: index ++

step 4: repeat step 2 to step 3 while i < 256

Explanation / Answer

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;


public class CountCharacter {

    public static void main(String[]args) throws FileNotFoundException, IOException
    {
        String filename=args[0];
        Scanner sc=new Scanner(new File(filename));
        int charCount[]=new int[256];
        int index;
        while(sc.hasNext())
        {
            String str=sc.next();
            for(int i=0; i<str.length(); i++)
            {
                index=(int)str.charAt(i);
                charCount[index]++;
            }
        }
        FileWriter fw = new FileWriter(args[1]);
        BufferedWriter bw = new BufferedWriter(fw);
        for(int i=0; i<256; i++)
        {
            if((i>=0 &&i<=32) || i==127 ||charCount[i]==0) {
            } else
            {
                char x=(char)i;
                System.out.println(i);
                bw.write(x+" "+charCount[i]+" ");
            }
        }
        sc.close();
        bw.close();
    }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote