[英]Why does not my count method return false when it is supposed to?
I have coded a class where you have a start and an end as inputs, and where a counter counts either up or down depending on whether the start value is smaller or bigger than the end value.我编写了一个 class 代码,其中您有一个开始和结束作为输入,并且计数器根据起始值是小于还是大于结束值来向上或向下计数。 When the counter has reached the end value, it should return false, if not it should return true.当计数器达到结束值时,它应该返回 false,如果没有,它应该返回 true。
When I run this in a junit test my professor has made, it says "After reaching the end value, the count() method should return false".当我在教授所做的 junit 测试中运行它时,它说“达到最终值后,count() 方法应该返回 false”。 I don't understand what is wrong with code.我不明白代码有什么问题。
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;
isValid();
if(start<end) {
this.increment = 1;
}
else {
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) {
this.counter == 0;
return false;
}
else {
return true;
}
}
public String toString() {
return "[counter = " + counter + "]";
}
public static void main(String [] args){
UpOrDownCounter c = new UpOrDownCounter(3, 5);
System.out.println(c.toString());
}
What happens to this.increment
if start == end
?如果start == end
, this.increment
会发生什么? We need to call isValid(), so that the counter doesn't blow past either end of the range.我们需要调用 isValid(),以便计数器不会超出范围的任何一端。 Change your constructor to:将您的构造函数更改为:
UpOrDownCounter(int start, int end) throws IllegalArgumentException {
this.start = start;
this.end = end;
this.counter = start;
isValid();
if(start<end) {
this.increment = 1;
} else {
this.increment = (-1);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.