-4

The Question: Find the frequency of dice rolls (meaning what number is rolled) for 600 dice rolls. This is the code that I have so far, and I seem to be stuck somewhere, but I just can't figure out where the error is located; if someone could help me out that would be great.

public class diceroll 
{

    /**
     * 
     */
    public static void main(String[] args) 
    {
        int toRoll = 600, x,i=0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0,
        c6 = 0;
        double pct1, pct2, pct3, pct4, pct5, pct6;

        for (i=0;i<=toRoll; i++)
        {
            x = (int)(Math.random()*6)+1;
            if (x==1)
                c1++;
            else if (x==2)
                c2++;
            else if (x==3)
                c3++;
            else if (x==4)
                c4++;
            else if (x==5)
                c5++;
            else if (x==6)
                c6++;
        }
        pct1 = (c1 * 100.0) / (double)toRoll;
        pct2 = (c2 * 100.0) / (double)toRoll;
        pct3 = (c3 * 100.0) / (double)toRoll;
        pct4 = (c4 * 100.0) / (double)toRoll;
        pct5 = (c5 * 100.0) / (double)toRoll;
        pct6 = (c6 * 100.0) / (double)toRoll;

        System.out.printf("Face\tFrequency\t%\n");
        System.out.printf("-------------------\n");
        System.out.printf("1\t%d\t%10.1f\n", c1);
        System.out.printf("2\t%d\t%10.1f\n", c2);
        System.out.printf("3\t%d\t%10.1f\n", c3);
        System.out.printf("4\t%d\t%10.1f\n", c4);
        System.out.printf("5\t%d\t%10.1f\n", c5);
        System.out.printf("6\t%d\t%10.1f\n", c6);

    }
}
FoolishSeth
  • 3,953
  • 2
  • 19
  • 28

3 Answers3

1

Use Random.nextInt(6), rather than Math.random() * 6.

See this question for why, if in doubt.

Community
  • 1
  • 1
Harald K
  • 26,314
  • 7
  • 65
  • 111
1

Your problem is that you are printing the outputs completely wrong.

The correct way to print out a % sign is by using %%, see the Formatter javadoc. Without escaping this variable it thinks you are trying to use some special syntax. After fixing that you need to print your actual perctanges, not the roll counts that you are currently using.

System.out.printf("Face\tFrequency\t%%\n");
System.out.printf("-------------------\n");
System.out.printf("1\t%f\t%%10.1f\n", pct1);
System.out.printf("2\t%f\t%%10.1f\n", pct2);
System.out.printf("3\t%f\t%%10.1f\n", pct3);
System.out.printf("4\t%f\t%%10.1f\n", pct4);
System.out.printf("5\t%f\t%%10.1f\n", pct5);
System.out.printf("6\t%f\t%%10.1f\n", pct6);

Also as smaller issues,

  1. You don't need to cast to a double here

    pct1 = (c1 * 100.0) / (double)toRoll; should become pct1 = (c1 * 100.0) / toRoll;

  2. The preferred way to get a random number from 1 to 6 is

    random.nextInt(6)+1;

greedybuddha
  • 7,488
  • 3
  • 36
  • 50
0

You missed the pctx values at printing.

Try print with

System.out.printf("1\t%d\t%10.1f\n", c1, pct1);
...