Java Counter Problems
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 + '}';
}
}
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.
This should work:
public void setValue(int newcount) {
if ((newcount < 0) || (newcount > maxValue))
return;
counter = newcount;
}
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;
}
public void setValue(int newcount)
{
if(newcount >= 0 && newcount <= maxcount)
{
count = newcount;
}
}
精彩评论