Consider the following code:
import java.util.*;
public class Main {
static final int ITEMS = 13;
static final int CAPACITY = (int) (Math.ceil(ITEMS*1.3));
static HashMap<String,Integer> h = new HashMap<String,Integer>(CAPACITY);
public static void main(String[] args) {
initHashMap();
printHashMap();
}
public static void initHashMap() {
String keyInt;
for (int i = 0; i < 1000; i++) {
keyInt = "" + ((int) (Math.random() * ITEMS));
if (h.get(keyInt) == null) {
h.put((keyInt + ""), 1);
} else {
h.put((keyInt + ""), (Integer) (h.get(keyInt)) + 1);
}
}
}
public static void printHashMap() {
Set keySet = h.keySet(); // returns all keys in the HashMap
Iterator iter = keySet.iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object value = h.get(key);
System.out.println(key + ": " +
", hashcode = " + key.hashCode() +
", occurrences = " + value);
}
System.out.println(h.keySet());
System.out.println(h.values());
}
public static String getItem(String s) {
return "" + ((Integer) (h.get(s)));
}
}
- Run this code.
- What can be said about the order of the items in your HashMap? Why?
- Is there anything recognizable about the hash codes? How so?
- Here is the definition of a histogram.
- Write a class called Die. (That's the singular form of the word "dice" for those of you who loathe ambiguity.) The Die class should have the following:
- A constructor that takes a number of sides as its input;
- An appropriate field to store that number of sides;
- A method roll() that randomly generates a number between 1 and the number of sides--you will need to be clever with Math.random(); you can decide whether roll() should be of type void or type int;
- A method getValue() that returns result that roll() produced; if a Die has not been rolled, getValue() should return 0.
- Here is code for a Main class that can be used as-is (i.e., no reason to change this).
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
Display disp = new Display();
disp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
disp.setVisible(true);
}
}
- Create a Display class that extends JFrame. This class will be where the bulk of your work needs to be done.
- Write a method called histogram() in the Display class which rolls four dice 1000 times and displays the sums of these rolls in a histogram. You will need an HashMap to store results. Fancy colors are unnecessary. Just make clear what the numbers are and that the bars are of appropriate length.
- Write any other methods needed in Display to make the histogram program work.