java - 计数器方法不递增
问题描述
我正在做一个练习,我的主程序看起来像这样,它使用一个计数器类来打印一个数字列表,直到它达到我在创建对象时给出的限制,然后返回到 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++;
}
}
}
我的 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;
}
}
解决方案
你需要一个else
:
if (this.value <= upperLimit) {
this.value+=1;
} else {
this.value = 0;
}
推荐阅读
- r - 如何使用 Rmarkdown 防止 pdf 输出中的连字符?
- ios - 如何在 iOS/Swift/Xcode 中播放一次抽签动画然后从帧循环到帧?
- c++ - crypto++ 可以同时使用 [Private]key 对象[在多线程中]
- .net - Nuget 项目上的黄色三角形?无法解析此引用。找不到程序集“NHibernate”
- javascript - 尝试使用 Tempermonkey 随机更改 Steam 背景,总是出现“Parsing Error: Unexpected Token”错误
- html - 特定的 HTML 标题属性值使元素消失
- javascript - 输入数据后我的表格显示不正确
- javascript - fullpage.js - Fp-auto-height 中间部分在单击anchor 和 moveTo() 最后一部分时没有达到其实际高度
- node.js - 如何获得相关的 package.json 依赖项以在 Windows 上使用 AWS 的 sam build 命令?
- ruby-on-rails - Rails 查询 CRON 作业的列表