我有一个计数器代码,它应该有方法来添加一个并减去一个。我必须确保代码永远不会低于0.我在想某个地方的计数器> = 0插件。或者它应该在我的驱动文件中?无论如何这里是代码。第一个片段是我认为必须保持积极的#34;声明应放在。
它应该在这部分吗?
public void minusOne(int count)
{
one -= count;
}
整个守则:
public class Counter
{
private int count;
private int one = 1;
public Counter()
{
count = 0;
}
public void addOne(int count)
{
one += count;
}
public void minusOne(int count)
{
one -= count;
}
public void setCounter(int count)
{
this.count = count;
}
public int getCounter()
{
return count;
}
}
答案 0 :(得分:0)
因此,如果one
变为否定,请将其重新设置为zero
public void minusOne(int count)
{
one -= count;
if (one < 0)
one = 0;
}
答案 1 :(得分:0)
public class Counter {
private int count;
public Counter() {
count = 0;
}
public void addOne() {
count++;
}
public void minusOne() {
if(count > 0) {
count--;
}
}
public void setCount(int count) {
if(count >= 0) {
this.count = count;
} else {
this.count = 0;
}
}
public int getCount() {
return count;
}
}