2010-09-28 40 views
-1

对于公共无效setValue(int newcount)我该如何使其它程序发送的值用于设置newcount?另外我必须这样做“如果newcount为<为零或> maxValue,则什么也不做。”Java计数器问题

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 + '}'; 
    } 
} 
+0

如果这是一个家庭作业问题,请标记为“作业” – 2010-09-28 20:04:36

+0

在'decrement()'中您的意思是:if(count == 0)count = maxValue;'?另外,为什么不使用模运算?例如'count =(count + 1)%maxValue','count =(count + maxValue - 1)%maxValue'。 – 2010-09-28 20:21:40

回答

0
public void setValue(int newcount) 
{ 
    if(newcount >= 0 && newcount <= maxcount) 
    { 
     count = newcount; 
    } 
} 
1

我像什么这样做有点糊涂:

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

它似乎并没有实际上是递减的价值。实际上,因为count == maxValue,所以没有必要设置它。

+0

是的,应该是'if(count == 0)'。而构造函数应该是'this.maxValue = maxValue'。 – 2010-09-28 20:11:21

1

这应该工作:

public void setValue(int newcount) { 
    if ((newcount < 0) || (newcount > maxValue)) 
    return; 
    counter = newcount; 
} 
+0

啊,沉默的失败。 OP要求的是什么,但却是一个愚蠢的要求......在这里抛出一个IllegalArgumentException可能更好。 – 2010-09-28 20:10:10

+0

是否有理由检查阴性病例(例如本答案)与检查阳性病例(例如我的答案)? – 2010-09-28 20:18:18

+0

@Mark Peters - yes :-)客户对我的要求负责 – 2010-09-29 04:34:53

1

你的构造不会做你的意思是要做到:

private int maxValue; 

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

你的代码只是设置其参数为零,参数名隐藏属性(以及为什么它设置为0)

什么工作,加入@param javadoc的线,是:

private int maxValue; 

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