Create a Class called CharacterCounter that provides char co

Create a Class called CharacterCounter that provides char counts for any text file (file used as constructor parameter).

Use a custom data structure CharInt.java that implements Comparable<CharInt> and Comparator<CharInt>, to provide the correct sorting as described below (i.e. TreeMap is not sorted correctly).

SUBMIT:

CharacterCounter.java

CharInt.java

One easy way to do this is to write a CharInt Class with two fields, Character and Integer, which implements Comparable to sort via count instead of char. When you have a Set (or Map) with a Character key, it will be alphabetical, and we require sorting by count, thus the need for this \"custom\" CharInt Class.

Requirements:

DO NOT use Map.Entry nor the entrySet() method (***below)

Keep with the Map concept for toString() output like { c=i } where c is the Character and i is the Integer count of c

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 overloaded (char or int or default) getCounts method that returns a Collection of character counts (see test code below: char returns count of that char, int returns highest of that many or lowest when negative, default() returns the entire Collection). Test code below:

Collection defined: use any List, Set, or Map that makes this easiest for you.

Hints:

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.

Solution

public class CountLetters { public static void main(String[] args) throws Exception { TreeMap hashMap = new TreeMap(); File file = new File(\"C:/text.txt\"); Scanner scanner = new Scanner(file,\"utf-8\"); while (scanner.hasNext()) { char[] chars = scanner.nextLine().toLowerCase().toCharArray(); for (Character c : chars) { if(!Character.isLetter(c)){ continue; } else if (hashMap.containsKey(c)) { hashMap.put(c, hashMap.get(c) + 1); } else { hashMap.put(c, 1); } } } for (Map.Entry entry : hashMap.entrySet()) { System.out.println(entry.getKey() + \": \" + entry.getValue()); } } }
Create a Class called CharacterCounter that provides char counts for any text file (file used as constructor parameter). Use a custom data structure CharInt.jav

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site