Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

View RSS Feed

JD1's Personal Development Blog

Array Elements As Counters - JavaDevelopmentForums.com

Rate this Entry
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
Categories
Uncategorized

Comments