Question

Write a Java program called Histogram.java that displays a list of distinct characters in an input tile and the occurrence of each eharacte. Your iogram should 1ead an input file name from a use. After that, your program should read characters in the file and display a list of distinct characters and their occurTeces. Finally, your program should draw a veril bafo the occuences For the assignment, your program has.to display the result exactly as the sample run. For instance, when you display a list of character occurrences, your program should display the characters with more than zero occurrence in the ascending order. The height of the vertical bar should be the same as the maxium value ofOccurrence And aksa the characters in th vertical bar should cone i te order of occurrences. In other words, since the characters from D to K have occurrence 0, it comes first. After that, characters . A and .C come next because ther occurrences are Finally, Bİs displayed because ts occurrence is 3. In the assignment, you can assume that the number of characters in the input file is less than 200. Yau can also assume that each line has only one character and theres no extra blank Furthermore, you can assume that all characters are capitals and from A to K space after each character This is another sample run of your progranm: Input filenamei Ctmpt2.txt A sample run of your program MUST be like below: Input tilename: C:\\tnp\tl.txt Char Occurrence vertical Bar 12 I 12 For the sample un, tl.txt has the following context: For the sample t2. txt has the following context:

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

Code to copy:

import java.io.*;

import java.util.Arrays;

//Define the class Histogram.

public class Histogram

{

    //Define the class to evaluate character frequency.

    class CFrequency implements Comparable<CFrequency>

    {    

    //Define the member variables for

        final char alphabet;

        int counter;

       

        //Create the constructor.

        public CFrequency(char alphabet)

        {

        //Set alphabet and counter.

            this.alphabet = alphabet;

            this.counter = 0;

        }

       

        //Define the method to increase the counter.

        void increment()

        {

            counter++;

        }

       

        //Define the method for getting the counter value.

        @Override

        public int compareTo(CFrequency obj)

        {

            return counter - obj.counter;

        }

    }

   

    //Define the character array to store the characters.

    CFrequency[] chararr;

    //Define the method to sort the array.

    void sortCharArray()

    {    

       //Sort array by using the sort function.

        Arrays.sort(chararr);

    }

   

    //Define the method to read the file.

    void readFile(File file) throws IOException

    {    

       //Create an object of buffered reader.

        BufferedReader brobj = new BufferedReader

                             (new FileReader(file));

       

        //Define a variable to get the file name.

        String readline;

       

        //Read the file line by line.

        while ((readline = brobj.readLine())!=null)

        {

            int ch = readline.charAt(0) - 'A';

            chararr[ch].increment();

        }

    }

   

    //Define the method to display the histogram.

    void displayHistogram()

    {    

        int maxLength = chararr[10].counter;

       

        //Print the upper part.

        System.out.println();

        System.out.println("=============Vertical Bar"

                             + "==============");

       

        //Print the number, characters and * as per the

        //conditions.

        for (int iterI = maxLength; iterI >= 1; iterI--)

        {

            if (iterI < 10)

            System.out.print("| ");

            else

                System.out.print("| ");

            System.out.print(iterI+ " | ");

            System.out.print(" ");

            for (int iterJ = 0; iterJ < 11; iterJ++)

                if (chararr[iterJ].counter >= iterI)

                    System.out.print(" * ");

                else

                    System.out.print("   ");

            System.out.println();

        }

        System.out.println("====================="

                             + "==================");

        System.out.print("| No | ");

        for (int jIter = 0; jIter < 11; jIter++)

            System.out.print(" " + chararr[jIter].alphabet

                               + " ");

        System.out.println();

       

        //Print the lower part.

        System.out.println("======================="

                             + "================");

    }

   

    //Define a method to display the character frequency.

    void displayCharFrequency()

    {

        System.out.println("Char Occurrence");

        for (int iIter = 0; iIter < 11; iIter++)

            if (chararr[iIter].counter > 0)

                System.out.println(" " +

                    chararr[iIter].counter + ""

                    + "      " + chararr[iIter].counter);

    }

   

    //Create the constructor of the class histogram.

    public Histogram()

    {

        chararr = new CFrequency[11];

       

        //Add the character in the character array.

        for (int iIter = 0; iIter < 11; iIter++)

            chararr[iIter] = new CFrequency

                             ((char)('A' + iIter));

    }

   

    //Define the main method.

    public static void main(String[] args) throws IOException

    {    

       //Define the variable to get filename.

        String fName;

       

        //Create an object of buffered reader.

        BufferedReader brobj = new BufferedReader

                        (new InputStreamReader(System.in));

        System.out.print("Input filename: ");

       

        //Read the filename.

        fName = brobj.readLine();

        System.out.println();

       

        //Create an object of the file.

        File Nfile = new File(fName);

     

        //Create an object of the class histogram.

        Histogram hobj = new Histogram();

       

        //Read the file.

        hobj.readFile(Nfile);

       

        //Display character frequency.

        hobj.displayCharFrequency();

       

        //Sort the character array.

        hobj.sortCharArray();

       

        //Display the histogram.

        hobj.displayHistogram();

    }

}

Add a comment
Know the answer?
Add Answer to:
Write a Java program called Histogram.java that displays a list of distinct characters in an input...
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
  • JAVA 6. Create two files and name them: puzzle.txt and puzzle2.txt Inside puzzle.txt, write the following...

    JAVA 6. Create two files and name them: puzzle.txt and puzzle2.txt Inside puzzle.txt, write the following text: MWTaahyiebt_e,c__hnyaoontuc;'e_rste_r_aynr_oert_e_gasoduoipdnp_got_shoeandtl__yty_oot_uhrree__apTdrH_oItgRhrDia_sml__eowtnotere.kr_ss_. Inside puzzle2.txt, write the following text: WTTohhriikssi__niigss,___ttbhhueet___wryrioogunh'gtr__emm_eessshssoaawggieen__gff_rrtoohmme___sswaarmmoppnllgee_22o..nttexxstt Open a file specified by the user. This file will contain a bunch of characters. You should read in each character from the file, one character at a time. Display every third character on the screen. Throw the other characters away. There is a sample input file called puzzle.txt, containing a little message you can...

  • In Java, write a program that prompts the user to input a sequence of characters and...

    In Java, write a program that prompts the user to input a sequence of characters and outputs the number of vowels. You will need to write a method to return a value called isAVowel which will return true if a given character is a vowel and returns false if the character is not a vowel. A second method, called isAConstant, should return true if a given character is a constant and return false if the character is not a constant....

  • Write a new program (hw6-pr1) meeting at least the following minimum requirements: Opens the text version...

    Write a new program (hw6-pr1) meeting at least the following minimum requirements: Opens the text version of this file (hw6-Spring2017.txt) and searches thru the file for the first occurrence of each of the 26 uppercase characters of the alphabet (A-Z), then each the 10 digits (0-9), and finally each of the 26 lowercase characters of the alphabet (a-z). As it finds each of these characters it should also record its position in the file (assume the first character in the...

  • Write a program in java to read a string object consisting 300 characters or more using...

    Write a program in java to read a string object consisting 300 characters or more using index input Stream reader. The program should perform following operations. The String must have proper words and all kind of characters.(Use String class methods). a, Determine the length of the string count the number of letters in the strings , count the number of numeric object d. Calculate the number of special character e. Compute the ratio of the numeric to the total f....

  • java program: Write a program which displays the following list on the screen and asks the...

    java program: Write a program which displays the following list on the screen and asks the user to enter either 1 or 2 and perform one of the operations based on the user’s input. If the user enters any other character other than 1 or 2 then display “wrong choice”. LIST OF OPERATIONS 1. Buzz Number                      2. Consecutive Odd numbers Note: A BUZZ number is a number which either ends with 7 or is divisible by 7. Sample input 27...

  • Write a C++ program called ts.cpp that implements the topological sorting algorithm based on the DFS...

    Write a C++ program called ts.cpp that implements the topological sorting algorithm based on the DFS algorithm. Your program should read an input file name and determine if the input graph is a DAG (= directed acyclic graph) or not. If the graph is not a DAG, your program has to stop without further processing. However, if it’s a DAG, your program should display the starting node(s), popping-off order, and topologically sorted list. In the problem, you can assume that...

  • This is for C++ Write a program that reads in a sequence of characters entered by...

    This is for C++ Write a program that reads in a sequence of characters entered by the user and terminated by a period ('.'). Your program should allow the user to enter multiple lines of input by pressing the enter key at the end of each line. The program should print out a frequency table, sorted in decreasing order by number of occurences, listing each letter that ocurred along with the number of times it occured. All non-alphabetic characters must...

  • Using basic c++ write 2 separate codes for this assignment. Program #1 Write a program that...

    Using basic c++ write 2 separate codes for this assignment. Program #1 Write a program that calculates the average of a group of test scores, where the lowest score in the group is dropped. It should use the following functions. • void getScore() should ask the user for a test score, store it in the reference parameter variable, and validate it. This function should be called by the main once for each of the five scores to be entered. •...

  • This assignment tests your ability to write C programs that handle keyboard input, formatted console output,...

    This assignment tests your ability to write C programs that handle keyboard input, formatted console output, and input/output with text files. The program also requires that you use ctype functions to deal with the logic. In this program, you will input from the user two characters, which should both be letters where the second letter > the first letter. You will then input a file character-by-character and output those letters that fall between the two characters (inclusively) to an output...

  • FOR JAVA Write a program that takes two command line arguments: an input file and an...

    FOR JAVA Write a program that takes two command line arguments: an input file and an output file. The program should read the input file and replace the last letter of each word with a * character and write the result to the output file. The program should maintain the input file's line separators. The program should catch all possible checked exceptions and display an informative message. Notes: This program can be written in a single main method Remember that...

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