java - 我如何设置一个限制,以便它能够按用户设定的数量停止循环?

标签 java

//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/

相关文章:

java - Bash 逐行读取文件,按制表符拆分,发送到 java 应用程序

java - 像在eclipse中一样在intellij想法中关闭未使用的模块

java - 显示收集不同 bean 的报告

Java:创建圈子

java - 将结果集转换为 MongoDB 中用户定义的数据结构

java - 在插件运行之前运行插件执行

java - 恢复 Windows 命令提示符

java - 关于并发 HashMap 的内部工作

java - 在 libGDX 中作为动画运行时,不同大小的纹理区域会反弹

java - 禁用 Spring mvc 自动序列化