public class DecreasingCounter {
private int value; // instance variable that remembers the value of the counter
int valueInitial;
public DecreasingCounter(int valueAtStart) {
this.value = valueAtStart;
}
public void reset(){
this.value = 0;
}
public void setInitial(){
this.valueInitial = 0;
}
}
我需要使用对象变量将值更改回DecreasingCounter(x);
setInitial();
中的值,但我不知道如何。
答案 0 :(得分:2)
这似乎是valueInitial
的用途:
public DecreasingCounter(int valueAtStart) {
this.valueInitial = valueAtStart;
this.value = valueAtStart;
}
public void setInitial(){
this.value = this.valueInitial;
}
您将初始值存储在构造函数中(分配给this.valueInitial
)并将其恢复为setInitial()
。
您不希望将this.valueInitial
设置为0
,因为这会导致您丢失在构造函数中设置的初始值。
答案 1 :(得分:0)
您可以添加变量来保存当前号码。 你所有的领域都会记得"它们的值(与函数/方法中创建的变量不同)。 您应该将初始值存储在valueInitial中,然后仅篡改value-variable。 像这样:
public class DecreasingCounter {
private int value; // instance variable that remembers the value of the counter
int valueInitial;
public DecreasingCounter(int valueAtStart) {
this.valueInitial = valueAtStart;
this.value=this.valueInitial;
}
public void reset(){
this.value = 0; //Not sure what you want to do here
}
public void countDown(){
this.value--;
}
public void setInitial(){
this.value = this.valueInitial;
}
}
答案 2 :(得分:0)
public class DecreasingCounter { private int value; // instance variable that remembers the value of the counter int valueInitial;
public DecreasingCounter(int valueAtStart) { this.valueInitial = valueAtStart; this.value = valueAtStart; }
public void reset() { this.value = 0; }
public void setInitial() { this.value = this.valueInitial; } }