Java, a program that counts a random number and stores it

I am trying to create a program that allows the user to choose how many times they want to roll the dice and then have to count each value of the dice rolled. At the end of the program, the user should see how many times he has thrown 1, 2, 3, etc. This is a program to see if each issue has an equal chance of being shown.

I am having problems at the beginning of my code, since I don't know how to let the computer roll the dice, say 1000 times, and then store each value from those rolled dice. This is what I have so far:

import java.util.Scanner;

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();

    int [] dice = { 1, 2, 3, 4, 5, 6 };
    int random = 0;

    for (int i = 0; i < amount; i++)
    {
        random = (int) (Math.random () + 1);
    }





}

      

}

The problem I'm running into is that it only stores one random number and then the number of cycles 6 times. As you can see, I haven't gotten far, I just need to know how I can save and recalculate every die I roll. And then I think I'm going to use a switch and case to save this somehow (any suggestions out there would be helpful too). Any suggestions or answers would be helpful. Thank.

+3


source to share


5 answers


I would use a HashMap to store the throw value (1 to 6), and also to store the number of times you got that value (incrementing one for each):

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();

    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(entry.getKey() + ": " + entry.getValue());
    }

}

      

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

The second for-loop calculates the X number of cubes and adds them to the hashmap.

The third for-loop iterates through the values โ€‹โ€‹in the hashmap and outputs the results.

Output:

How many times do you want to throw the dice:
500
1: 92
2: 88
3: 72
4: 78
5: 81
6: 89

      

EDIT: If you want to get the mean and mean, you can do the following:



double average = 0;
int[] storedSums = new int[6];

int i = 0;
for (Map.Entry<Integer, Integer> entry : rolls.entrySet()) {
    int sum = entry.getValue();
    average += sum;
    storedSums[i++] = sum;
    System.out.println(entry.getKey() + ": " + sum);
}

Arrays.sort(storedSums);

System.out.println("Average: " + (average / 6));
System.out.println("Median: " + storedSums[2]);

      

Average is simply the process of adding values โ€‹โ€‹and dividing by the sum. However, the median with the hashmap is somewhat more complicated. The best choice here is to use Array or ArrayList to store different values, then sort them and finally select the middle element (either index 2 or 3).

I chose an array in this case because we know its size.

EDIT: Regarding your last request:

To get the bones that match the median value, I simply convert the array to a list and use the indexOf method with a known value:

int medianDice = Arrays.asList(storedSums).indexOf(storedSums[2]);
System.out.println("Median: " + storedSums[2] + ", which belongs to dice: " + medianDice + ".");

      

It is a little more difficult to get the bone value for the mean (since this number is not represented by one of the stamps). You will need to use the average to find the closest value in the array, and then print the index for that value.

+3


source


you can use ArrayList

to store random numbers and then process them as needed.

List<Integer> listOfNumbers = new ArrayList<>(amount);
Random generator = new Random();
for (int i = 0; i < amount; i++)
{
     listOfNumbers.add(generator.nextInt(7));
}

      



Also, your current algorithm for random numbers is not correct, you must use a class Random

to generate random numbers between 1 - 6

(inclusive).

+1


source


You are writing the same value over and over random

int

, so use an array int

to store the values โ€‹โ€‹like below:

int[] random = new int[amount];//declare an array
Random randomNumber =  new Random();
for (int i = 0; i < amount; i++) {
    random[i] = randomNumber.nextInt(7);
}

      

Also, use java.util.Random nextInt()

with an upper bound (in your case the max value for a bone might be 6, so use the upper bound as 7) to generate random numbers as shown above.

+1


source


import java.util.Scanner;
import java.util.Random;

public static void main(String[] args){
    Scanner inputReader = new Scanner(System.in);
    System.out.println("How many times do you want to roll the dice:");
    int num_rolls = inputReader.nextInt();
    int NUM_SIDES_ON_DICE = 6;
    int[] results = new int[NUM_SIDES_ON_DICE]
    Random rand = new Random();
    for (int i = 0; i < num_rolls; i++) {
        results[rand.nextInt(NUM_SIDES_ON_DICE)] += 1
    }
    for (int i = 0; i < dice.length; i++) {
        System.out.println("Number of " + (i+1) + " thrown: " + results[i]
    }
}

      

0


source


Stream version:

        new Random()
        .ints(amount, 1, 7).boxed()
        .collect(Collectors.groupingBy(s -> s))
        .forEach((k, v) -> System.out.println(k + ": "+v.size()));;

      

0


source







All Articles