2010-09-28 41 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; 
}