Java counter

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

Sounds like you can narrow down the problem more. Find out which operation is “not working” and then consider what should have happened vs what does happen (the difference may tell you what you should change)

No great mystery here, you just gotta have a look at what does happen and compare to what you want.

You can add prints in your code to write out what is being done. Consider what should happen and then add prints which show that happening.

Oh and note that code is rather sensitive to change. When you share code you have to ensure that you are sharing an exact copy – it appears someone had to edit your post for you to make that so.