// Counter.java // Solution to SA #5 by THC. Based on the Counter class example. // Implementation of the class Counter. // Define a class of Counter objects. A Counter holds a single integer // in the range 0..(myLimit - 1). Each time tick() is called the // Counter increases, wrapping back to 0 when it reaches myLimit. // Note: The show method always displays at least 2 digits, padding with // a leading 0 if necessary. If the value of the Counter is >= 100, then // the show method will display as many digits as necessary. That means // that the columns of the successive Counter values displayed will not // line up correctly when the Counter transitions from 99 to 100. import java.text.DecimalFormat; public class Counter { private int myLimit; // Upper limit on the counter private int myValue; // Current value // Constructor for the Counter class. // Create a Counter with myLimit set to limit and // myValue set to 0. public Counter(int limit) { myLimit = limit; myValue = 0; } // Display the value of a Counter, padding with a leading 0 if necessary. public void show() { DecimalFormat fmt = new DecimalFormat("00"); // Use at least 2 digits System.out.print(fmt.format(myValue)); } // Increment the value of a Counter, wrapping around if it // hits the limit. public void tick() { myValue++; if (myValue == myLimit) // Has it hit the limit? myValue = 0; // Wrap if it has } // Advance the value of a Counter, wrapping around as appropriate. // The parameter gives how far to advance the value, and it may be negative. public void advance(int amount) { myValue = (myValue + amount) % myLimit; // If the counter ends up being negative, it will be between -1 and -myLimit. // Just add in myLimit to correct the value. if (myValue < 0) myValue = myLimit + myValue; } }