1.2.10

1.2.10 Develop a class VisualCounter that allows both increment and decrement operations. Take two arguments N and max in the constructor, where N specifies the maximum number of operations and max specifies the maximum absolute value for the counter. As a side effect, create a plot showing the value of the counter each time its tally changes
import edu.princeton.cs.algs4.StdDraw;

public class E1210 {
    public static class VisualCounter 
    {
        private final int N;
        private final int Max;
        private int times = 0; //记录操作次数
        private int count = 0;//计数器值
        //构造函数
        public VisualCounter(int n,int max) throws Exception{
            times = 0;
            if (max < 0)
                throw new Exception("请保证输入的max值为非负数");
            else
            {
                this.Max = max;
                this.N = n;
                //建立坐标轴
                StdDraw.setCanvasSize(400,400);
                StdDraw.setXscale(0,n+1);
                StdDraw.setYscale(-(max+1),max+1);
                StdDraw.point(0, 0);
            }
        }
        //加1操作
        public void increment() {
            if (!overMax() && !overN()) this.count++;
            else {
                System.out.println("已满足终止条件!");
                System.exit(0);
            }
        }
        //减1操作
        public void decrement() {
            if (!overMax() && !overN()) this.count--;
            else {
                System.out.println("已满足终止条件!");
                System.exit(0);
            }
        }
        //获取当前计数值
        public int getcount(){
            return this.count;
        }
        //获取当前操作次数
        public int gettimes(){
            return this.times;
        }
        //判断当前count是否超过Max
        public boolean overMax(){
            if (Math.abs(this.count)<this.Max) return false;
            return true;
        }
        //判断当前操作次数是否超过最大次数
        public boolean overN(){
            if (this.times < this.N) return false;
            return true;
        }
        //绘制点
        public void draw(){
            StdDraw.point(this.times, this.count);
        }
    }
    public static void main(String[] args) throws Exception {
        int n = 200;
        int max = 100;
        VisualCounter counter = new VisualCounter(n, max);
        StdDraw.setPenRadius(0.2);
        for(int i = 0; i < 120;i++)
        {
            counter.increment();
            counter.draw();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值