views:

85

answers:

4

For the public void setValue(int newcount) how do I make it so the value the other program sends is used to set the newcount? Also I have to do this "If the newcount < zero or > maxValue, do nothing."

    private int maxValue;
    private int count;

    /**
    * Constructor for objects of class Counter
    */
    public Counter(int maxValue) 
    {
        maxValue = 0;
    }

    public void decrement()
    {
       if (count == maxValue)
       {
           count = maxValue;        
       }
       else
       {
           --count;
       }
    }

   public int getValue() 
    {
        return maxValue;
    }

   public void increment()
    {
       if (count  == maxValue)
       {
           count = 0;        
       }
       else
       {
           ++count;
       }
    }

    public void setValue(int newcount) 
    {


    }


   public String toString()
    {
        return "Counter{" + "maxValue=" + maxValue + '}';
    } 
}
A: 
public void setValue(int newcount) 
{
   if(newcount >= 0 && newcount <= maxcount)
   {
      count = newcount;
   }
}
MikeG
+1  A: 

I'm a little confused as to what this does:

 public void decrement()
{
   if (count == maxValue)
   {
       count = maxValue;        
   }

It doesn't seem to actually be decrementing the value. In fact since count == maxValue, there is no point in setting it.

Vasto
Yeah that should probably be `if (count == 0)`. And the constructor should probably be `this.maxValue = maxValue`.
Mark Peters
+1  A: 

This should work:

public void setValue(int newcount) {
  if ((newcount < 0) || (newcount > maxValue))
    return;
  counter = newcount;
}
Andreas_D
Ahh, silent failures. Exactly what the OP asked for but a silly requirement...probably better to throw an IllegalArgumentException here.
Mark Peters
Is there a reason why it is better to check the negative cases (e.g. this answer) vs. check for positive cases (e.g. my answer)?
MikeG
@Mark Peters - yes :-) The customer is responsible for the requirements
Andreas_D
@MikeG - usually I validate the input parameters at the very beginning of a method - so I just follow my 'personal' style.
Andreas_D
I'm with @Andreas_D on this style. It puts the actual method's logic in the main level of indentation, with the conditional logic only for exceptional circumstances. It's weird to me when the normal thing a method does is nested in if statements.
Mark Peters
+1  A: 

Your constructor does not do what you meant it to do:

private int maxValue;

/**
* Constructor for objects of class Counter
*/
public Counter(int maxValue) 
{
    maxValue = 0;
}

Your code just sets its argument to zero, the argument name hides the attribute (and why set it to 0?)

What would work, adding the @param javadoc line, is:

private int maxValue;

/**
 * Constructor for objects of class Counter.
 * @param newMaxValue The maximum counter value.
*/
public Counter(int newMaxValue) 
{
    maxValue = newMaxValue;
}
rsp