Algs4-1.2.10编写一个类VisualCounter

1.2.10编写一个类VisualCounter,支持加一和减一操作。它的构造函数接受两个参数N和max,其中N指定了操作的最大次数,max指定了计数器的最大绝对值。作为副作用,用图像显示每次计器变化后的值。
答:Draw Point时操作次数作为X坐标,计数器值作为Y坐标。
图片
图片

public class VisualCounter
{
    private int maxOperationTimes;
    private int maxCountAbs;
    private int operationTimes;
    private int count;
   
    public VisualCounter(int N,int max)
    {
        maxOperationTimes=N;
        maxCountAbs=max;
        operationTimes=0;
        count=0;
    }  
   
    public void increment()
    {
       if (operationTimes<maxOperationTimes && Math.abs(count)<maxCountAbs)
       {
          operationTimes++;
           count++;
        }
    }
   
    public void decrease()
    {
       if (operationTimes<maxOperationTimes && Math.abs(count)<maxCountAbs)
       {
          operationTimes++;
           count--;
        }
    }
   
    public int tally()
    {
        return count;
    }
   
    public int operationTimes()
    {
        return operationTimes;
    }
   
    public boolean isEnd()
    {
      return  operationTimes>=maxOperationTimes || Math.abs(count)>=maxCountAbs ;
    }

    public void draw()
    {
        StdDraw.point(operationTimes,count);
    }


   
    public static void main(String[] args)
    {
        int N=Integer.parseInt(args[0]);
        int max=Integer.parseInt(args[1]);
        VisualCounter vC=new VisualCounter(N,max);
        int num;
        StdDraw.setXscale(0,N);
        StdDraw.setYscale(-1.0*max,max);
        while (true)
        {
            num=StdRandom.uniform(max/17);
            for(int j=0;j<num;j++)
            {
                 if (num%2==0)
                     vC.increment();
                 else
                     vC.decrease();  
                 vC.draw();
                 if(vC.isEnd()) return;
            }
       }
    }
}

posted @ 2018-10-25 11:40  修电脑的龙生  阅读(257)  评论(0编辑  收藏  举报