Write a program which uses a for statement to simulate 120000 rolls of two dice. 'Keep track' of the number of times each possible outcome (a total in the range 2 to 12) is rolled using 11 integer variables. After all the rolls output a table showing the number of times each possible outcome occurred. For example

Total Number of times rolled
--------------------------------
2 3451
3 6795
...

Dani AI

Generated

and are on the right track. A clean, bug-resistant way is to map each possible sum (2..12) directly to an array index so you avoid lots of separate variables and off-by-one errors. Use a single pass of 120000 iterations, generate two dice each iteration, increment the count for the sum, then print the counts and percentages.

Example (concise) simulation:

import java.util.concurrent.ThreadLocalRandom;

int[] counts = new int[13]; // use indices 2..12
for (int i = 0; i < 120000; i++) {
    int a = ThreadLocalRandom.current().nextInt(1, 7);
    int b = ThreadLocalRandom.current().nextInt(1, 7);
    counts[a + b]++;
}

for (int sum = 2; sum <= 12; sum++) {
    System.out.printf("%2d %7d %6.2f%%%n", sum, counts[sum], counts[sum] * 100.0 / 120000);
}

Notes and quick checks:

  • Use an array of length 13 so counts[sum] is direct. This avoids manual mapping and the risk of incorrect indices.
  • ThreadLocalRandom.current().nextInt(1, 7) returns 1..6 (upper bound exclusive). See the ThreadLocalRandom javadoc.
  • Expected probabilities: number of combos for a sum s is 6 - Math.abs(7 - s). So expected counts ≈ 120000 * combos / 36 (for example, sum=7 ≈ 20000, sum=2 ≈ 3333).
  • Quick sanity checks: total of all counts should equal 120000; if not, check index use and random bounds. For reproducible runs use a seeded Random instead of ThreadLocalRandom.

Recommended Answers

All 2 Replies

>Create variables to hold how many times each value occured:

int countOf2s = 0;
int countOf3s = 0;
...

>Create a method that returns a random number from 1 to 6
> inside a for loop (it will be executed 12000) call the above methods 2 times, add their results and depending on the outcome increase by 1 the appropriate variable
> the loop will be repeated and in the end will have the number of occurences stored at the variables
> print those variables

Do what JavaAddict suggested, I would suggest one minor modification though: use an integer array of size 12 (one for each value) to keep track of the number of times each has occurred. Simply increment the index- increment index 0 if you see a 1, index 1 if you see a 2, and so on.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.