Tutorial
Menus

Java Beginners - Java For Beginners

Java Random Numbers

Rating: 0.0/5 (0 votes cast)

Level   : Beginners
Author : Arunkumar S
Download Source : Not Avaliable

Java Random Numbers

Random Number Exercise: Dice Roller



If you started at the beginning, you have made it through a good portion of the Focus on Java Java   Programming Tutorial. In addition to basic language features such as conditionals and operators, you have learned about classes and methods. Now, let us put what we have learned to use. This is the first of several programming exercises in the tutorial. Each is designed to help you apply the lessons and concrete them into your mind.

Write a class named dice.Die that represents a single die roll and can return its number of sides and its rolled value. The class should be immutable—meaning it must be instantiated with all of its properties defined in its constructor and these properties must not be modifiable.

Die must have one public constructor that defines its number of sides and its rolled value via parameters.

public Die(int numberOfSides, int valueRolled)  

Die must have two public methods for getting its properties:

public int getValueRolled()   public int getNumberOfSides()  

Next, write a class named dice.DieRoller. It must have one public method with the following signature:

 public Die roll(int sides)  

When called, roll() must return a new instance of dice.Die that represents the value rolled. This number must be a random int in the range 1 to sides where sides is the number of sides the die has (and that was passed into roll() as an argument). Feel free to use either Math.random() or Random class.

Finally, write a dice.DieRollerExample class that uses Die and DieRoller to roll different dice combinations. For instance, a 6 sided die, two 6 sided dice, a 20 sided die, etc. For extra credit, write a simple craps game based on the roll of two dice.


< Previous 1 | 2 | 

Discussion about this tutorial

  Start a new Discussion | Read All Discussion
Subject RepliesLast Post
Javaorigin.com contact@javaorigin.com