Array Elements As Counters - JavaDevelopmentForums.com
by
, January 29th, 2012 at 05:07 PM (4912 Views)
We're going to build a program to re-enact a dice being rolled one thousand times. We're going to output how many times each face of the dice is rolled.
import java.util.Random; class RollDice{ public static void main(String args[]){ Random rand = new Random(); int freq[] = new int[7]; for(int roll = 1; roll <= 1000; roll++){ ++freq[1 + rand.nextInt(6)]; } System.out.println("Face\tFrequency"); for(int face = 1; face < freq.length; face++){ System.out.println(face + "\t" + freq[face]); } } }
First of all, we have to import our random class. Then, we create a new random number object called rand. We create a new integer array called freq. We set this equal to 7 because we want the numbers 1-6. 7 Will give us 0-6 but we'll just ignore the zero.
Next up is our for loop set to iterate one thousand times. In that we increment the index of our frequency array by a random number ranging from 1 through to 6. This line of code stores the values of each face of the die.
We then output a header (face and frequency) separated by a tab and create a small for loop to output the face and value of each face. This is really just six iterations.
Java Development Forums