Write a program that uses a HashMap to compute a histogram of positive numbers entered by the user. The HashMap’s key should be the number that is entered, and the value should be a counter of the number of times the key has been entered so far. Use -1 as a sentinel value to signal the end of user input. For example, if the user inputs:

5
12
3
5
5
3
21
-1
Then the program should output the following (not necessarily in this order):
The number 3 occurs 2 times.
The number 5 occurs 3 times.
The number 12 occurs 1 times.
The number 21 occurs 1 times.

The solution is a fairly straightforward implementation of a HashMap to map a number to a counter. It may be worth mentioning that equals and hashcode must be overwritten if the student wants to use HashMap with their own set. Note that Java will automatically unbox/box between an int and Integer. This solution takes advantage of this feature.

See the code in HashMapHistogram.java.

Computer Science & Information Technology

You might also like to view...

Use the ________ data type when you do not know how much text space will be required

Fill in the blank(s) with correct word

Computer Science & Information Technology

Which method call converts the value in variable stringVariable to an integer?

a. Convert.toInt(stringVariable) b. Convert.parseInt(stringVariable) c. Integer.parseInt(stringVariable) d. Integer.toInt(stringVariable)

Computer Science & Information Technology