Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 计数器方法不递增_Java_Class_Counter_Increment - Fatal编程技术网

Java 计数器方法不递增

Java 计数器方法不递增,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

我在做一个练习,我的主程序看起来像这样,它使用一个计数器类来打印一个数字列表,直到它达到我创建对象时给出的限制,然后返回到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 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。大多数时候你不需要
这个。