gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:18:50 26 4
gpt4 key购买 nike

好的,我有一个家庭作业问题。我正在构建一个在我的讲师提供的测试人员类(class)中使用的类(class)。它只不过是一个基本的计数器。我已经将计数器设置为测试人员传递到我的类(class)的数字工作正常并且输出符合预期。但是,我的类必须将初始计数设置为 0,并将默认增量/减量设置为 1。

这是我的类(class):

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());
}

}

最佳答案

第一次实例化 Counter 类时,您的 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
}

关于java - 如何在Java中设置默认的增量/减量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14532292/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com