import java.util.Random; /** * This class represents a single n-sided die. The top number of the die is called * the "face value". You can roll the die or you can explicitly set the die to a * particular face value. * * @author alchambers * @version sp16 */ public class Die { // Instance variables private Random rng; private int numSides; private int faceValue; /** * This is the default constructor. It defaults to a 6-sided die. */ public Die(){ numSides = 6; rng = new Random(); roll(); // class methods can call each other without using the dot operator } /** * This constructor creates a new n-sided die * @param sides The number of sides of the die */ public Die(int sides){ numSides = sides; rng = new Random(); roll(); // class methods can call each other without using the dot operator } /** * Simulates a roll of the dice * @return the number rolled */ public int roll(){ int newValue = rng.nextInt(numSides)+1; // a local variable faceValue = newValue; return faceValue; } /** * Allows user to explicitly set the die to whatever value they want * @param newValue the new face value of the die */ public void setFaceValue(int newValue){ faceValue = newValue; } /** * Returns the current face value of the die * @return the current face value */ public int getFaceValue(){ return faceValue; } /** * Returns a String that summarizes the state of the die * @return a string representation of the state of the die */ public String toString(){ String stateOfDie = "[face=" + faceValue + ", sides=" + numSides + "]"; return stateOfDie; } /** * Compares this die to the other die. The result is true if both die * have the same number of sides and the same face value. * @param other The die to compare against * @returns true If this die and the other string are equal, false otherwise */ public boolean equals(Die other){ int otherFaceValue = other.faceValue; int otherNumSides = other.numSides; if(faceValue == otherFaceValue && numSides == otherNumSides){ return true; } return false; // Below is a one-line alternative // return (faceValue == otherFaceValue) && (numSides == otherNumSides); } }