Hi all,
I’m in an intro Java course and I’m having trouble with a homework problem. In summary: my counterPlusOne method, which is part of my Counter class, doesn’t appear to be working correctly when I call it in my CounterTest program. I would love help figuring out why.
Let me lay everything out though. Here is the problem:
Problem 2:
Define a class called Counter. An object of this class is used to count things so it records a count that is a non-negative whole number. Include methods to set the counter to 0, to increase the counter by 1, and to decrease the counter by 1. Be sure that no method allows the value of the counter to become negative. Also include an accessor method that returns the current count value, as well as a method that displays the count on the screen. Do not define an input method. The only method that can set the counter is the one that sets it to zero. Write a program to test your class definition. (Hint: you need only one instance variable).
Here is my Counter class:
public class Counter
{
private int count;
public void setCounterToZero()
{
count = 0;
}
public void counterPlusOne()
{
count = count++;
}
public void counterMinusOne()
{
if (count > 0)
count = count--;
else
System.out.println("Error - count cannot be less than zero");
}
public int getCount()
{
return count;
}
public void displayCount()
{
System.out.println(count);
}
}
And here is my CounterTest program, which is a different file but saved in the same directory as my Counter class:
public class CounterTest
{
public static void main(String[] args)
{
Counter counter = new Counter();
counter.setCounterToZero();
counter.displayCount();
counter.counterPlusOne();
counter.counterPlusOne();
counter.displayCount();
}
}
What displays is:
0
0
So, clearly counter.counterPlusOne() is not having the desired affect.
Any help would be appreciated. Thanks!
- Cliff