CS174: OOP - Drills - Character Counting with HashMaps

Developed by Professor Tralie and Professor Mongan.

Exercise Goals

The goals of this exercise are:
  1. Put key/value pairs into a HashMap data structure
  2. Use loops in concert with strings
Fill in the method countChars that creates a HashMap whose keys are the unique characters in a given string and whose corresponding values are the number of occurrences of that character in the string.

Enter your Ursinus netid before clicking run. This is not your ID number or your email. For example, my netid is ctralie (non Ursinus students can simply enter their name to get this to run, but they won't get an e-mail record or any form of credit)

Netid
Clicking Run below will check your work and, if it passes, will submit your work automatically. You must be connected to the VPN for submission to be successful! You will receive a copy of your code via e-mail, so you'll know that it was submitted if you receive that e-mail!

StringUtils.java

public class StringUtils { /** * Create a HashMap data structure whose keys are the unique * characters in a string and whose values are the number of * occurrences of each character in the string * @param s The string to process * @returns A hash map with key as the character and the value * as the count of that character **/ public static HashMap<Character, Integer> countChars(String s) { HashMap<Character, Integer> countMap = new HashMap<>(); // TODO: Fill this in with a for loop return countMap; } }

Driver.java

public class Driver { public static void main(String[] args) { String s = "hello and welcome to cs 173"; HashMap<Character, Integer> countMap = StringUtils.countChars(s); System.out.print('o='+countMap.get('o')); System.out.print("."); System.out.print('e='+countMap.get('e')); System.out.print("."); System.out.print('l='+countMap.get('l')); System.out.print("."); System.out.print('t='+countMap.get('t')); System.out.print("."); System.out.print(' ='+countMap.get(' ')); } }
Driver.main(null);

Output