Search code examples
javahashmapaveragemediancalculation

Java, calculation of median and average when using Math.random


My program lets the user choose how many times he want to throw the dice, then the program prints out how many times he got each side of the dice.

So far everything is good, but then I have to calculate the median and the average of all these thrown dice, and I want both the average and the median to range from 1-6 corresponding to how many sides a dice has - how do I do that?

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Uppgift4_5 
{
    public static void main(String[] args) 
    {
        Scanner inputReader = new Scanner(System.in);
        System.out.println("How many times do you want to throw the dice:");
        int amount = inputReader.nextInt();
        System.out.println("Antal försök:" + amount);

        Map<Integer, Integer> rolls = new HashMap<>();

        for (int i = 1; i < 7; i++) 
        {
            rolls.put(i, 0);
        }

        for (int i = 0; i < amount; i++) 
        {
            int value = (int) (Math.random() * 6 + 1);
            rolls.put(value, rolls.get(value) + 1);
        }

        for (Map.Entry<Integer, Integer> entry : rolls.entrySet()) 
        {
            System.out.println(("Antal kast som gav "+entry.getKey()) + ": " + entry.getValue());
        }
    }
}

The first for-loop initializes the keys 1 to 6 in the hashmap.

The second for-loop computes X number of dice throws and adds them to the hashmap.

The third for-loop iterates through the values in the hashmap and prints out the results.


Solution

  • For calculating average you can use below code :

    double average=0;
    double total=0;
    for (Map.Entry<Integer, Integer> entry : rolls.entrySet()) 
    {
        total+=entry.getKey()*entry.getValue();
        System.out.println(("Antal kast som gav "+entry.getKey()) + ": " + entry.getValue());
    }
    
    average = total/amount;
    System.out.println("Average : "+average);