1

This java program generates a random number between 1-6. It also allows the user to choose how many random numbers between 1-6 to generate. I now need to record and output how many instances of each number came up. ie. How many times each number 1,2,3,4,5,6 came up in a single run of the program. How would I go about doing this? Here is what I have so far.

import java.util.Random;

public class DiceRandomness {
    public static void main(String[] args) {
        Random generator = new Random();

        System.out.print("How many throws of the dice: ");
        int num = Console.readInt();

        int[] Results = new int[10000];

        for (int i = 0; i < num; i++) {

            int d = 1 + generator.nextInt(6);
            System.out.println(d + " ");
        }
    }
}
2
  • 10
    I'd create an array of 6 ints and increment the array entry corresponding to the number picked. Commented Nov 26, 2013 at 18:58
  • or 7 to avoid the off by one - and just use counter[result] instead of counter[result-1] Commented Nov 26, 2013 at 19:01

2 Answers 2

4

Hopefully this hint will help you:

int[] counters = new int[6];
for (int i = 0; i < num; ++i)
{

}
Sign up to request clarification or add additional context in comments.

3 Comments

@PeterLawrey that looks familiar
@PeterLawrey: That would be a huge memory waste :P
@MartijnCourteaux but save some -1 and +1 in places.
0

Instead of storing the random number in d, store it to the Results array "Results[i]" that way each answer will get stored in the next index of the array.

Then put the print statement in a seperate for loop to print out the results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.