Java 计数器方法不递增
我在做一个练习,我的主程序看起来像这样,它使用一个计数器类来打印一个数字列表,直到它达到我创建对象时给出的限制,然后返回到0。 我希望它返回0,1,2,3,4,5,然后循环回0,但它所做的一切都给了我0Java 计数器方法不递增,java,class,counter,increment,Java,Class,Counter,Increment,我在做一个练习,我的主程序看起来像这样,它使用一个计数器类来打印一个数字列表,直到它达到我创建对象时给出的限制,然后返回到0。 我希望它返回0,1,2,3,4,5,然后循环回0,但它所做的一切都给了我0 public class Main { public static void main(String args[]) { BoundedCounter counter = new BoundedCounter(5); System.out.println("value at
public class Main {
public static void main(String args[]) {
BoundedCounter counter = new BoundedCounter(5);
System.out.println("value at start: "+ counter);
int i = 0;
while (i< 10) {
counter.next();
System.out.println("Value: "+counter);
i++;
}
}
}
公共类主{
公共静态void main(字符串参数[]){
BoundedCounter计数器=新的BoundedCounter(5);
System.out.println(“开始时的值:+计数器”);
int i=0;
而(i<10){
counter.next();
System.out.println(“值:+计数器);
i++;
}
}
}
我的BoundedCounter类是这样的
public class BoundedCounter {
private int value;
private int upperLimit;
public BoundedCounter(int Limit) {
upperLimit = Limit;
}
public void next(){
if (this.value <= upperLimit) {
this.value+=1;
}
this.value = 0;
}
public String toString() {
return "" + this.value;
}
}
公共类边界计数器{
私有int值;
私有整数上限;
公共边界计数器(整数限制){
上限=上限;
}
下一个公共空间(){
如果(this.value您需要一个else
:
if (this.value <= upperLimit) {
this.value+=1;
} else {
this.value = 0;
}
if(this.value您需要将this.value=0
放在else语句中,因为它每次都被执行
修改代码:
public void next(){
if (this.value <= upperLimit) {
this.value+=1;
}
else
this.value = 0;
}
public void next(){
如果(this.value)你的next
方法总是将value
设置为0,试着调试你的程序,看看next
方法中哪个行是this.value
设置为0
。(注意:这不是Python。大多数时候你不需要这个。
)