// OPP 中用于演示代码的计数器类,它应该与提供的代码一起使用,但输出都是错误的,setLimit 不会限制任何东西
public class CounterExtended {
private int value;
/**
* Gets the current value of this counter.
*
* @return the current value
*/
public int getValue() {
return value;
}
/**
* Advances the value of this counter by 1.
*/
public void count() {
value = value + 1;
}
/**
* Resets the value of this counter to 0.
*/
public void reset() {
value = 0;
}
public void setLimit(int maximum) {
if (value >= maximum)
System.out.printf("Limit of",maximum, "exceeded");
}
public void undo() {
if (value>=0){
value--;
}
}
}
和演示代码
public class Demo {
public static void main(String[] args) {
CounterExtended tally = new CounterExtended();
for (int i = 1; i <= 10; ++i) {
if (i > 7) {
tally.setLimit(6);
}
tally.count();
System.out.printf("After count %d, tally is %d\n", i,
tally.getValue());
}
tally.undo();
tally.undo();
tally.count();
System.out.printf("After 2 undo's and one count, tally is %d\n",
tally.getValue());
}
}
运行上面的代码后,输出应该看起来像
After count 1, tally is 1
After count 2, tally is 2
After count 3, tally is 3
After count 4, tally is 4
After count 5, tally is 5
Limit of 5 exceeded
After count 6, tally is 5
Limit of 5 exceeded
After count 7, tally is 5
After count 8, tally is 6
Limit of 6 exceeded
After count 9, tally is 6
Limit of 6 exceeded
After count 10, tally is 6
After 2 undo's and one count, tally is 5