0

好的,所以我有一个家庭作业问题。我正在构建一个用于我的讲师提供的测试员课程的课程。它只不过是一个基本的计数器。我已经将计数器设置为测试人员传递给我的班级的数字工作正常并且输出符合预期。但是,我的班级必须将初始计数设置为 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());
    }

}
4

1 回答 1

2

第一次实例化它时,您的 Counter 类中没有无参数构造函数,所以这样做

Counter counter = new Counter(0,1);

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

或者您可以提供一个无参数构造函数:

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
}
于 2013-01-26T00:09:41.010 回答