Java类,试图创建一个找到初始值的方法

标签 java

我刚刚开始学习类(class),我有点卡住了。我不知道如何让这个方法找到第一次输入的初始值

public class DecreasingCounter {
    private int value;

    public DecreasingCounter(int valueAtStart) {
        this.value = valueAtStart;
    }

    public void printValue() {
        // do not touch this!
        System.out.println("value: " + this.value);
    }

    public void decrease() {
        if (this.value > 0) {
            this.value--;
        }
    }

    public void reset() {
        this.value = 0;
    }

    public void setInitial() {
        this.value = 
    }
}

这是我尝试开始工作的最后一个方法setInitial();

最佳答案

您只需要以成员身份维护对初始值的引用,以便稍后可以再次引用它。

private final int initialValue;

然后像这样修改你的构造函数

public DecreasingCounter(int valueAtStart) {
    //store the initial value based on the arg passed in
    this.initialValue = valueAtStart; 

    //go ahead and do whatever we do to reset our counter to the 
    //initial value (avoids duplicating code)
    this.setInitial(); 
}

最后,

public void setInitial() {
    //reset our current value back to the initial value we stored at construction time
    this.value = this.initialValue;
}

关于Java类,试图创建一个找到初始值的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41324899/

相关文章:

java - Spring + Hibernate = 未知实体

java - 更新/重新创建 JList

java - 使用循环 (for) 添加 JButton 不会执行任何操作

java - 将 byte[] 转换为 BitSet

java - 为什么Thread.join使用currentTimeMillis?

java - 如何在java中重新缩放图像?

java - 在 Mac OS X 上最小化后 JFrame 不刷新

java - I18N 属性上的 org.springframework.context.NoSuchMessageException

java - Tomcat 环境变量 - 是否可以使它们永久存在?或者在重新部署时不会丢失?

java - 如何使用java在谷歌应用程序引擎中创建docx文件