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

Find maximum char count, with Map sorted by counts: Building on Exercise #15 tha

ID: 3913732 • Letter: F

Question

Find maximum char count, with Map sorted by counts:

Building on Exercise #15 that uses a Map to count int data, let's create a Class called CharCounter that provides char counts for any text file (input file used as constructor parameter).

Character == ASCII char's that exist in a text file

Integer == count of each char in that data file

At issue is the fact that TreeMap<Character, Integer> would be sorted by Character, but we want this sorted by the Integer count of each Character. And you cannot just flip that to TreeMap<Integer, Character> because identical Integer counts will omit the first occurrence!!!

SUBMIT: CharCounter.java

A good place to start is definitely Exercise 11.15, however, we might then get a HashMap<Character, Integer> but that has some strange ordering. But a TreeMap<Character, Integer> would be sorted alphabetically, so the first three elements could be a,b,c regardless of their counts. We desire the sorting to be by the count of those characters in the text file! One way to change this is to make a Comparator<K> (Links to an external site.) that is used to sort a TreeMap<Character, Integer>

Requirements:

DO NOT (immediate zero) use Map.Entry and DO NOT use .entrySet() Only because I know this is a very well know online solution that I prefer you do not just copy past and submit. We need to write our own code and learn from such composition

Keep with the Map concepts, so the toString() output looks like { c=i } where c is the Character and i is the Integer count of c, using braces. Know well to those who know it well, Java Maps use { } while Sets and Lists use brackets [ ]

Ignore case for alphabetic characters, report just a-z (meaning a-z are the same as A-Z).

Other characters such as tabs, returns, line feeds, spaces (there will be many spaces) also count.

Use the constructor to read a data file (see testing code below)

Provide a simple getCounts() method that returns a Map of character counts (see test code below), plainly showing the highest character counts first.

Provide a constructor that accepts a Scanner so I can pass in any other Scanner that I desire for final code testing after submissions.

Additional Information of above:

Use a small test file (like 10 characters) where you know the answers for initial testing. Especially because that's how your instructor will grade these.

Look at what Wikipedia (Links to an external site.)Links to an external site. says for most common char's, your results should be close?

Someone start a Discussion on counts, so we can share results, but do not post code, just counts...

Explanation / Answer

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks

// CharCounter.java

import java.util.Comparator;

import java.util.Scanner;

import java.util.TreeMap;

public class CharCounter {

                // treemap of character,integer key values

                private TreeMap<Character, Integer> counts;

                /**

                * constructor to initialize the counter

                *

                * @param scanner

                *            - scanner ready to read the contents from

                */

                public CharCounter(Scanner scanner) {

                                /**

                                * initializing the map

                                */

                                counts = new TreeMap<Character, Integer>();

                                /**

                                * iterating through all lines

                                */

                                while (scanner.hasNext()) {

                                                // getting a line

                                                String line = scanner.nextLine();

                                                for (int i = 0; i < line.length(); i++) {

                                                                // adding all characters to the map

                                                                char c = line.charAt(i);

                                                                if (Character.isLetter(c)) {

                                                                                // converting to upper case

                                                                                c = Character.toUpperCase(c);

                                                                }

                                                                // calling the method to add

                                                                add(c);

                                                }

                                                if (scanner.hasNext()) {

                                                                // adding a next line character

                                                                add(' ');

                                                }

                                }

                                sort(); // sorting by values, using a comporator

                }

                /**

                * method to sort the map by values

                */

                private void sort() {

                                Comparator<Character> comparator = new Comparator<Character>() {

                                                @Override

                                                public int compare(Character c1, Character c2) {

                                                                int a = counts.get(c1);

                                                                int b = counts.get(c2);

                                                                if (a < b) {

                                                                                return 1;

                                                                }

                                                                return -1;

                                                }

                                };

                                /**

                                * creating a temporary map which is using the above comporator

                                */

                                TreeMap<Character, Integer> sortedMap = new TreeMap<Character, Integer>(

                                                                comparator);

                                /**

                                * adding all elements in counts to this map

                                */

                                sortedMap.putAll(counts);

                                //replacing the existing counts with sorted values

                                counts = (TreeMap<Character, Integer>) sortedMap.clone();

                }

                /**

                * method to add a char to the map

                * @param c will be added with count 1 if not exists, else updates the count

                */

                private void add(char c) {

                                if (counts.containsKey(c)) {

                                                counts.put(c, counts.get(c) + 1);

                                } else {

                                                counts.put(c, 1);

                                }

                }

                /**

                *

                * @return the map

                */

                public TreeMap<Character, Integer> getCounts() {

                                return counts;

                }

}

// Test.java

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Test {

                public static void main(String[] args) throws FileNotFoundException {

                               

                                Scanner data = new Scanner(new File("input.txt"));

                                // reads data from file, all the code to read file

                                CharCounter working = new CharCounter(data);

                                // returns the Map, sorted by highest char count first

                                System.out.println(working.getCounts());

                }

}

/*OUTPUT*/

{ =49, E=36, T=31, S=31, O=26, R=24, I=19, A=15, N=13, C=10, -=9, U=8, F=8, P=7, L=7, H=7, D=7,

=4, J=3, B=3, Q=2, M=2, Y=1, K=1, G=1, ,=1}

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