import java.util.Random; // Warn Java we want to use Random /** * The Die class models a die of the sort you'd roll: It * can be created with as many sides as you wish, and has * a roll method that returns an appropriate random result. */ public class Die { // numSides CANNOT be made static without changing the behavior of the // class. We need to be able to have different numbers of sides for each // Die, so each needs its own copy of numSide. private int numSides; // rng COULD be static -- the program would still work correctly, But SHOULD // it be? We'd save some memory by only keeping one copy of Random. private static Random rng = new Random(); // It makes sense to make all constants static -- it would have the same value // across Die instances anyway. private static final int MAX_NUM_SIDES = 20; private static int numDice = 0; // HAS to be static for program to work properly /** * Constructor for objects of class Die. The default constructor * (this one, since it takes no parameters) will create a six-sided * die. */ public Die() { numSides = 6; numDice = numDice + 1; } /** * This constructor creates a Die object with the specified number * of sides. */ public Die(int sides) { if (sides > MAX_NUM_SIDES) { System.out.println("That's ridiculous. I'm using 6 instead"); numSides = 6; } else { numSides = sides; } numDice = numDice + 1; } /** * Simulates a roll of this Die instance. Picks a * random value in the appropriate range and returns it. */ public int roll() { int rollValue = rng.nextInt(numSides); return rollValue+1; } /** * Returns number of sides. Cannot be a static method since it * references a field that's not static. */ public int getNumSides() { return numSides; } /** * This method CAN be static, since it only accesses static fields. In * general, if a method CAN be static, it probably SHOULD be. */ public static int getNumDice() { return numDice; } }