The Random class in java can be very helpful for performing simulations and creating games. A basic way to use this class is to simulate a dice, which means getting a random number from a certain range depending on how many sides the dice contains. It’s fairly easy and quick to make, which means anyone with a decent knowledge of java could easily make it.

Steps

  1. Name it DiceSimulator. If it makes a main class automatically, call that class DiceTester.
    Advertisement
    • In this Dice file, import the random package: import java.util.Random;
    • Random randomGenerator = new Random();
    • int sides = 0;
    • public Dice (int numberOfSides) { sides = numberOfSides;}
    • public int roll() {int result = randomGenerator.nextInt(sides) + 1; return result; }
    • If DiceTester is your main class, go straight to DiceTester instead.
    • import java.util.Scanner;
  2. “How many dice do you need?”
    • If you're new to programming, use System.out.println(" "); to print statements.
    • int howManyDice = in.nextInt();
  3. “How many sides do each dice have?”
    • int howManySides = in.nextInt();
    • Within this loop, you construct each Dice object by using the for loop variable x and passing the variable howManySides.
    • for (int x = 0; x < howManyDice; x++) {theDice[x] = new Dice(howManySides); int result = theDice[x].roll(); System.out.println("Roll of dice #" + (1 + x) + ": " + result); }
    • In many IDE its by pressing the green play button on the top left corner of your IDE application.
    Advertisement

Expert Q&A

Ask a Question

      Advertisement

      Tips

      • Try to compile and run the program as you put new code in to find any errors in your program!
      • Keep your code organized so you can easily find certain areas of your code for later review.
      • Leave comments using // to leave information where you believe will need extra attention or for other programmers to look over your program!
      Advertisement

      About this article

      Thanks to all authors for creating a page that has been read 17,509 times.

      Is this article up to date?

      Advertisement