Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Counter class

807589Aug 30 2008 — edited Aug 31 2008
Counter 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
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 28 2008
Added on Aug 30 2008
12 comments
83 views