/* An instance of this class (UmpireClicker2) represents a hand-held ** mechanical device commonly used by baseball/softball umpires to keep ** track of the inning, outs, balls, and strikes during the course of a ** game. This version improves upon its predecessor (UmpireClicker1) ** by introducing the advanceCount() method that embodies the common ** logic of each of the four public mutators, thereby allowing each of ** those methods to be simplified. ** ** Author: Robert McCloskey ** Date: October 2020 */ public class UmpireClicker2 { // symbolic constants // ------------------ private static final int BALL_MAX = 4; private static final int STRIKE_MAX = 3; private static final int OUT_MAX = 3; private static final int INNING_MAX = 9; // instance variables (fields) // --------------------------- private int ballCntr; // for keeping track of the counts of private int strikeCntr; // balls, strikes, outs, and the inning private int outCntr; private int inningCntr; // constructor // ----------- /* Initializes the instance variables of a newly-created UmpireClicker2 ** object. (Because all of them are initialized to zero, which Java does ** automatically, this constructor can be omitted entirely, or, ** alternatively, its body can be made to be empty.) */ public UmpireClicker2() { ballCntr = 0; strikeCntr = 0; outCntr = 0; inningCntr = 0; } // observers // --------- // Because each method's name makes its purpose obvious, we omit comments. public int ballCount() { return ballCntr; } public int strikeCount() { return strikeCntr; } public int outCount() { return outCntr; } public int inningCount() { return inningCntr; } public String toString() { return "Inning " + inningCount() + ", Out " + outCount() + ", Ball " + ballCount() + ", Strike " + strikeCount(); } // mutators // -------- // Because each method's name makes its purpose obvious, we omit comments. public void advanceBallCount() { ballCntr = advanceCount(ballCntr, BALL_MAX); } public void advanceStrikeCount() { strikeCntr = advanceCount(strikeCntr, STRIKE_MAX); } public void advanceOutCount() { outCntr = advanceCount(outCntr, OUT_MAX); } public void advanceInningCount() { inningCntr = advanceCount(inningCntr, INNING_MAX); } // private methods // --------------- /* Returns the value that a "wraparound" counter should assume as a ** result of advancing it (by one unit). Given are the counter's ** current value and its maximum allowable value. ** Note: A wraparound counter is one whose set of possible values ** is the range 0..N, for some N, with 0 being the successor of N. */ private int advanceCount(int cntr, int MAX) { if (cntr < MAX) { return cntr + 1; } else { return 0; } } //Note: An alternative method body is this: return (cntr + 1) % (MAX + 1); }