I am working on a homework assignment for a class and I have solved almost all of it, but am struggling with one part.
For the assignment, we are supposed to write a program that will count the frequency of occurrence of letters in any given string and then print out a map of them to the console. I have written the program and it works almost correctly, but I cannot get the map to ignore whitespace. It seems to find two different kinds of whitespace as well, one that is the space between words and another that I cannot figure out.
I’ve tried myString.replaceAll(" ", ""); and myString.trim(); to try and eliminate the whitespace before counting the frequency of letters, but it still counts both types of whitespace each time.
Any insight or help is appreciated. I could turn it in like this, but I don’t like half-assing projects. Here is the code:
import java.util.*;
public class LetterFrequency {
public static void main( String[] args ) {
Map< String, Integer > myMap = new HashMap< String, Integer >();
createMap( myMap );
displayMap( myMap );
}
private static void createMap( Map< String, Integer > map ) {
Scanner scanner = new Scanner( System.in );
System.out.println( "Enter a string:" );
String input = scanner.nextLine();
System.out.println("String: "+input);
String[] tokens = input.split("");
for ( String token : tokens ) {
String letter = token.toLowerCase();
if ( map.containsKey( letter ) ) {
int count = map.get( letter );
map.put( letter, count + 1 );
}
else
map.put( letter, 1 );
}
}
private static void displayMap( Map< String, Integer > map ) {
Set< String > keys = map.keySet();
TreeSet< String > sortedKeys = new TreeSet< String >( keys );
System.out.println( "\nMap contains:\nKey\t\tValue" );
for ( String key : sortedKeys )
System.out.printf( "%-10s%10s\n", key, map.get( key ) );
System.out.printf(
"\nsize: %d\nisEmpty: %b\n", map.size(), map.isEmpty() );
}
}
String.replaceAllshould work. Keep in mind thatString.replaceAllreturns aString. So you have to use the string it returns to perform the rest of your computation.For instance, if you have:
myStringwill still be “hello world”You’d want:
After which
myNewStringwill have no spaces.Also, you can simplify your character iteration by using
This will fix your additional “whitespace being counted” problem. This is because when you call
myString.split(""), the first element in the returned list is “” (an empty string).