为什么我的count方法应该返回false?

问题描述 投票:0回答:1

我已经编写了一个类,在该类中,您有一个开始和一个结束作为输入,并且其中一个计数器根据起始值是小于还是大于终值来递增或递减计数。当计数器达到最终值时,它应该返回false,否则返回true。

[当我在教授进行的junit测试中运行此命令时,它说:“达到最终值后,count()方法应返回false”。我不明白代码有什么问题。

public class UpOrDownCounter {

    private int end;
    private int counter;
    private int start;
    private int increment;

    UpOrDownCounter(int start, int end){
        this.start = start;
        this.end = end;
        this.counter = start;

        if(start<end) {
            this.increment = 1;
        }
        if(start>end) {
            this.increment = (-1);
        }
    }

    public void isValid() throws IllegalArgumentException{
        if(this.start == this.end) {
            throw new IllegalArgumentException("the start value can't be the same as the end value");
        }
    }

    public int getCounter() {
        return counter;
    }

    public boolean count() {
        counter += increment;
        if(this.counter == end) {
            return false;
        }
        else {
            return true;
        }
    }

    public String toString() {
        return "[counter = " + counter + "]";
    }


}
java oop return boolean counter
1个回答
1
投票
UpOrDownCounter(int start, int end){ this.start = start; this.end = end; this.counter = start; if(start<end) { this.increment = 1; } else if (start>end) { this.increment = (-1); } else { this.increment = 0; } }
© www.soinside.com 2019 - 2024. All rights reserved.