如何在Java中设置默认的增量/减量值

时间:2013-01-26 00:07:09

标签: java

好的,所以我有一个家庭作业问题。我正在构建一个在我的讲师提供的测试器类中使用的类。它只不过是一个基本的反击。我已经将计数器设置为测试人员通过我的班级的数字工作正常并且输出正如预期的那样。但是我的类必须将初始计数设置为0,默认增量/减量为1。

这是我的班级:

public class Counter
{
    private int count;
    private int stepValue;

    /**
     * This method transfers the values called from CounterTester to instance variables
     * and increases/decreases by the values passed to it. It also returns the value
     * of count. 
     *
     * @param args
     */ 
    public Counter (int initCount, int value)
    {       
        count=initCount;
        stepValue=value;
    }   

    public void increase ()
    {
        count = count + stepValue;
    }

    public void decrease ()
    {
        count = count - stepValue;
    }

    public int getCount()
    {
        return count;
    }

}

以下是测试人员类:

public class CounterTester
{

    /**
     * This program is used to test the Counter class and does not expect any
     * command line arguments. 
     *
     * @param args
     */
    public static void main(String[] args)
    {
        Counter counter = new Counter();

        counter.increase();
        System.out.println("Expected Count: 1 -----> Actual Count: " + counter.getCount());

        counter.increase();
        System.out.println("Expected Count: 2 -----> Actual Count: " + counter.getCount());

        counter.decrease();
        System.out.println("Expected Count: 1 -----> Actual Count: " + counter.getCount());


        counter = new Counter(3, 10);
        System.out.println("Expected Count: 3 -----> Actual Count: " + counter.getCount());

        counter.increase();
        System.out.println("Expected Count: 13 ----> Actual Count: " + counter.getCount());

        counter.decrease();
        System.out.println("Expected Count: 3 -----> Actual Count: " + counter.getCount());

        counter.decrease();
        System.out.println("Expected Count: -7 ----> Actual Count: " + counter.getCount());
    }

}

1 个答案:

答案 0 :(得分:2)

第一次实例化Counter类时,你没有没有arg构造函数,所以

Counter counter = new Counter(0,1);

应该设置初始值和步长值。

或者你可以提供一个no-arg构造函数:

public class Counter
{
  private int count;
  private int stepValue;

  public Counter () { //no argument constructor - must be explictly made now
    count=0;
    stepValue = 1;
  }

  public Counter (int initCount, int value)
  {       
    count=initCount;
    stepValue=value;
  }  

  //rest of code
}