Search code examples
javaarrayssumcountingdice

3 Dice Sum Counting Program Java


For my Computer Science Class, my teacher is asking us to do the following:

Program Description: You are learning to play a new game that involves 3 six-sided die. You know that if you knew the probability for each of the possible rolls of the die that you’d be a much better competitor.

Since you have just been studying arrays and using them to count multiple items that this program should be a snap to write. This will be cool since the last time we did this we work just looking for how many times 9 or 10 could be rolled and this program won’t require any if statements.

Required Statements: output, loop control, array

Sample Output:

Number Possible Combinations

1 0

2 0

3 1

4 3

5 6

6 10

7 15

8 21

9 25

10 27

11 27

12 25

13 21

14 15

15 10

16 6

17 3

18 1

I can easily do this with an if statement, but I don't understand how to do it without one. It is especially tricky because under hints, she wrote: "These programs utilize a counting array. Each time a value is generated the position at that index is incremented. It’s like the reverse of the lookup table." I have no idea what this means.

Here's my code with the if statement:

public class prog410a
{
    public static void main(String args[])
    {
        System.out.println("Number\tPossible Combinations");

        for (int x = 1; x <= 18; x++)
        {
            int count = 0;
            for (int k = 1; k <= 6; k++)
            {
                for (int i = 1; i <= 6; i ++)
                {
                    for (int j = 1; j <= 6; j++)
                    {
                        if (k + i + j == x)
                            count++;
                    }
                }
            }
            System.out.println(x + "\t\t\t" + count);
        }

    }
}

So I guess my overall question is this: How can I emulate this, but by using some sort of array instead of an if statement?


Solution

  • You don't need the outer x loop. All you need is three nested loops, one for each die. You will also need an array of integers all initialized to zero. Inside the innermost dice loop, you just use the sum of the three dice as the index to you integer array and increment the value at that index.

    After you complete the dice loops, then you can iterate over your integer array and output the frequency of your results.