Search code examples
javafrequencybluejdiceloaded

What is the if statement for a frequency a number has shown up?


For example: If the number has been rolled 25% out of all the dice rolls, state (System.out.println("The dice might be loaded!")

import javax.swing.*;
class Dice
{
    public static void main (String [] args)
    {
            int c = Integer.parseInt(JOptionPane.showInputDialog("How many sides?"));
            int[ ] sides = new int[c];
            String[ ] number = new String[c];
            int max = c;
            int min = 1;
            int d = Integer.parseInt(JOptionPane.showInputDialog("How many times do you want to roll your dice?"));

            for(int i=0;i<c;i++)
            {
                number[i] = (JOptionPane.showInputDialog("Enter side number:"));
            }

            for(int i=0;i<d;i++)
            {
                int r;
                r = (int) Math.floor(Math.random() * max) + min;                System.out.println(r);

                sides[r-1] = sides[r-1] + 1;
            }

            for(int i=0;i<c;i++)
            {
                System.out.println(number[i] + " was rolled " + sides[i] + " times.");
            }
    }
}   

Solution

  • Keep track of the number of times the dice have been rolled and the number of times the result your looking for has been rolled. Then you can do

    if(thisRoll/totalRolls >= .25)
        doSomeStuff();
    

    Just make sure that at least one of the variables has decimal points, otherwise you'll have int/int division and always get 1 or 0.