//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
最佳答案
这显然是“学习练习”,因此仅提示:
您遇到的问题是弄清楚如何使您的计数器类在被提供的测试工具使用时按照示例输出运行。显然(其他读者请注意!)不允许更改测试工具。
输出暗示
count()
在发生溢出时应该做什么。 (提示:它不应该停止循环...)输出暗示
getValue()
应该在溢出后返回什么?您需要在
CounterExtended
实例中记录哪些额外状态才能实现此目的?CounterExtended
实例的当前实例字段是实现此目的的最佳方法吗? (提示:不……但您需要找出为什么它不是。)
关于java - 我如何设置一个限制,以便它能够按用户设定的数量停止循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16258294/