如何在Java中设置默认的递增/递减值
好的,我有一个家庭作业问题。我正在构建一个类,用于我的讲师提供的测试人员类。它只不过是一个基本计数器。我已经将计数器设置为测试人员传递给我的班级的数字可以正常工作,并且输出与预期一致。但是,我的类的初始计数必须设置为0,默认增量/减量为1 这是我的班级:如何在Java中设置默认的递增/递减值,java,Java,好的,我有一个家庭作业问题。我正在构建一个类,用于我的讲师提供的测试人员类。它只不过是一个基本计数器。我已经将计数器设置为测试人员传递给我的班级的数字可以正常工作,并且输出与预期一致。但是,我的类的初始计数必须设置为0,默认增量/减量为1 这是我的班级: public class Counter { private int count; private int stepValue; /** * This method transfers the values
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;
}
}
以下是tester类:
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());
}
}
第一次实例化计数器类时,计数器类中没有no-arg构造函数,也是这样
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
}
下次,您可能希望在帖子中添加一个问题。是的,我也尝试过,但在编译时,我收到错误消息“构造函数计数器()未定义”,这突出显示了Tester类中的“new Counter();”。我已经把这件事告诉了我的老师,她说她的代码是完美的,而我的代码是错误的。你必须将构造函数定义为
计数器
类的一部分。通常,如果不指定构造函数,默认情况下会提供一个无参数构造函数。当你明确地做一个时,它就消失了。因此,在您的关注下,您必须创建一个带参数的构造函数,一个不带参数的构造函数。好吧,我刚刚尝试了您的代码,它可以工作,但我对Java非常陌生,不明白为什么我必须创建两个相同的构造函数。@SkyVar阅读了上面评论中的解释。不,它们不是同一个构造函数,它们接受不同的参数:-)我想我现在明白了。因为我有两个构造函数(一个带参数,一个不带参数)调用计数器类,所以计数器类中必须有两个构造函数。