import java.util.*;
class Count {
private static final int SIZE = 6;
private static int[] freq;
private static int i;
public static Map<Integer, Integer> count() {
int[] freq = new int[SIZE];
for (i = 0; i < 100; i++) {
++freq[(int) (Math.random() * SIZE)];
}
return null;
}
public static void write(Map<Integer, Integer> map) {
for (int i = 0; i < SIZE; i++)
System.out.println("Dice eye = " + (i + 1) + ", Frequency = " + freq[i]);
}
}
public class Dice {
public static void main(String[] args) {
Map<Integer, Integer> map = Count.count();
Count.write(map);
}
}
I want to print out the frequency of dice eyes when I throw the dice 100 times using Hashmap. I know how to make a Count class, but I don't know how to organize the method. How to return the hashmap and save it?
An example of the output I want,
ex)
Dice eye = 1, Frequency = 15
Dice eye = 2, Frequency = 16
Dice eye = 3, Frequency = 12
Dice eye = 4, Frequency = 16
Dice eye = 5, Frequency = 25
Dice eye = 6, Frequency = 16
Create a method which converts yours freq array to HashMap
public static Map<Integer,Integer> Array_To_HashMap(){
Map<Integer,Integer> map= new HashMap<Integer, Integer>();
for(int i=0;i<SIZE;i++){
map.put(i+1,freq[i]);
}
return map;
}
Call this in count function. Your count class will look like this
public static Map<Integer, Integer> count() {
for (i = 0; i < 100; i++) {
++freq[(int) (Math.random() * SIZE)];
}
return Array_To_HashMap();
}
EDIT:-
class Count {
private static final int SIZE = 6;
private static int[] freq=new int[SIZE];
private static int i;
public static Map<Integer, Integer> count() {
for (i = 0; i < 100; i++) {
++freq[(int) (Math.random() * SIZE)];
}
return Array_To_HashMap();
}
public static Map<Integer,Integer> Array_To_HashMap(){
Map<Integer,Integer> map= new HashMap<Integer, Integer>();
for(int i=0;i<SIZE;i++){
map.put(i+1,freq[i]);
}
return map;
}
public static void write(Map<Integer, Integer> map) {
map.forEach((eye,frequency)->{
System.out.println("Dice eye = " + eye + ", Frequency = " + frequency);
});
}
}
public class Dice {
public static void main(String[] args){
Map<Integer, Integer> map = Count.count();
Count.write(map);
}
}