Hi,
I am taking my first Java class this semester, and I have run into an assignment that just has me stumped:
I am to write a program that will count the number of occurrences of each letter in a string the user inputs. It is in a section discussing Maps, HashMaps, StringTokenizers, and TreeSets, so I am assuming that I need to use these if possible.
Here is what I have so far:
/** Program that counts the number of occurrences of each letter.
* LetterTypeCount.java
*
*/
import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;
public class LetterTypeCount
{
private Map< String, Integer > map;
private Scanner scanner;
public LetterTypeCount()
{
map = new HashMap< String, Integer >(); // create HashMap
scanner = new Scanner( System.in ); // create scanner
createMap(); // create map based on user input
displayMap(); // display map content
} // end LetterTypeCount constructor
// create map from user input
private void createMap()
{
System.out.println( "Enter a string:" ); // prompt for user input
String input = scanner.nextLine();
// create StringTokenizer for input
StringTokenizer str = new StringTokenizer( input );
// process input text
while ( str.hasMoreTokens() ) // while more input
{
String symbol = str.nextToken().toLowerCase(); // get letter
// if the map contains the word
if ( map.containsKey( symbol ) ) // is letter in map
{
int count = map.get( symbol ); // get current count
map.put( symbol, count + 1 ); // increment count
} // end if
else
map.put( symbol, 1 ); // add new letter with a count of 1 to map
} // end while
} // end method createMap
// display map content
private void displayMap()
{
Set< String > keys = map.keySet(); // get keys
// sort keys
TreeSet< String > sortedKeys = new TreeSet< String >( keys );
System.out.println( "Map contains:\nKey\t\tValue" );
// generate output for each key in map
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() );
} // end method displayMap
public static void main( String args[] )
{
new LetterTypeCount();
} // end main
} // end class LetterTypeCount
It is almost working...my output counts the words in the string:
Enter a string:
Here is a string
Map contains:
Key Value
a 1
here 1
is 1
string 1
size:4
isEmpty:false
BUILD SUCCESSFUL (total time: 5 seconds)
I would like my output to list each letter on the left with the number of occurrences on the right. I am probably making an obvious mistake, but after looking at this all week, I've got nothing left.
Any advice?
P.S.
Since this is my first forum and first post, I hope I am following all of the appropriate guidelines. If not, please let me know.
Thank you!