Counter class
807589Aug 30 2008 — edited Aug 31 2008Counter increases and decreases by 1, records count nonnegative integer and tests whether the current count value is zero. No method allows the value of counter to become negative. Can anyone assist?public class Counter
{
private int count; // definition of counter
public Counter(int aCount) // Constructor to initialize count
{
count = aCount;
}
public void setCountToZero() //method to zero out counter
{
count = 0;
}
public void addOneToCount() //method to add one to counter
{
count += 1; // or count++;
}
public void subtractOneFromCount() //method to subtract one from counter
{
if ((count - 1) >= 0)
{count -= 1;} // or count--;
}
public void displayCount()
{
System.out.println("The count is " + count);
}
}
//tester
package counter;
public class CounterTest
{
public static void main(String[] args)
{
Counter myCounter = new Counter(-1); // Create myCounter Object and give 10 to counter
myCounter.displayCount(); // Displays the zero value
myCounter.addOneToCount(); // Now count has value of 11
myCounter.displayCount(); // Displays the zero value
myCounter.subtractOneFromCount(); // Subtracted one from count
myCounter.displayCount(); // Displays count
myCounter.setCountToZero(); // Resets count to zero
myCounter.displayCount(); // Displays the zero value
}
}