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); } }
Quiero imprimir la frecuencia de los ojos de los dados cuando lanzo los dados 100 veces usando Hashmap. Sé cómo hacer una clase Count, pero no sé cómo organizar el método. ¿Cómo devolver el hashmap y guardarlo?
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
Cree un método que convierta su matriz de frecuencias en 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; }
Llame a esto en la función de conteo. Su clase de conteo se verá así
public static Map<Integer, Integer> count() { for (i = 0; i < 100; i++) { ++freq[(int) (Math.random() * SIZE)]; } return Array_To_HashMap(); }
EDITAR:-
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); } }