Java:如何不允许变量低于0



我正在测试一个计数器类。计数器向上或向下递增1。但是,我不希望数字低于零,并且我希望在计数器设置为负值时输出一条错误消息。下面是我的计数器类的代码。此外,我不确定如何让布尔测试显示一个字符串,说明计数器的两个实例相等(或不相等)。谢谢你的帮助。

public class Counter {
private int counter;
public Counter() {
counter = 0;
}
//mutator adds 1 to counter
public void plus1(){
setCounter(getCounter() + 1);
}
//mutator subtracts 1 from counter
public void minus1(){
setCounter(getCounter() - 1);
}
//mutator
public void setCounter(int newCounter){
counter = newCounter;
}
//accessor
public int getCounter(){
return counter;
}
//polymorph
public String toString(){
return "The counter is currently at " + counter + ".";
}
public boolean equals(Counter a){
return this.getCounter() == a.getCounter();
}
}

让我逐一回答您的问题:

  • 不让计数器使用minus1()设置为-ve值:为此,您可以添加以下条件
if(counter == 0)
throw new IllegalStateException("counter already 0"); // could be another exception type
  • 不让计数器使用setCounter(newCounter)设置为-ve值
if(newCounter < 0)
throw new IllegalArgumentException("counter cannot be negative"); // could be another exception type
  • 布尔测试显示一个字符串计数器是否相等:

不确定您是否试图覆盖Object#equals方法,那么您的方法签名是错误的,可能是

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Counter that = (Counter) o;
return counter == that.counter;
}

你可以使用一些记录器来打印字符串

最新更新