/* * @topic T01065 Array of ordered Die objects * @brief class Die implements Comparable */ package demoa7v2; public class Die implements Comparable<Die> { public static final int DEFAULT_SIDE_COUNT = 6; private int faceValue; private int sideCount; private boolean sortByNumber; // constructor public Die() { sideCount = DEFAULT_SIDE_COUNT; faceValue = roll(); sortByNumber = true; } // operations public int roll() { faceValue = 1 + (int) ( Math.random() * getSideCount() ); return faceValue; } public int getSideCount() { return sideCount; } public int getFaceValue() { return faceValue; } public void setOrderByNumber( boolean value ) { sortByNumber = value; } @Override public int compareTo( Die another ) { //if ( !( another instanceof Die ) ) { // // this is an error // return -1; //} //Die anotherDie = (Die) another; if ( sortByNumber == true ) { // example of sorting by number if ( this.faceValue < another.faceValue ) { return -1; } else if ( this.faceValue == another.faceValue ) { return 0; } else { return 1; } } else { // example of sorting by string String myString = this.toString(); String anotherString = another.toString(); return myString.compareTo(anotherString); } } public String toString() { switch ( faceValue ) { case 1: return "one"; case 2: return "two"; case 3: return "three"; case 4: return "four"; case 5: return "five"; case 6: return "six"; default: return "BIG NUMBER"; } } }//class Die