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
importedu.princeton.cs.algs4.StdDraw;publicclass E1210 {publicstaticclassVisualCounter{privatefinalintN;privatefinalintMax;privateint times =0;//记录操作次数privateint count =0;//计数器值//构造函数publicVisualCounter(int n,int max)throwsException{
times =0;if(max <0)thrownewException("请保证输入的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操作publicvoidincrement(){if(!overMax()&&!overN())this.count++;else{System.out.println("已满足终止条件!");System.exit(0);}}//减1操作publicvoiddecrement(){if(!overMax()&&!overN())this.count--;else{System.out.println("已满足终止条件!");System.exit(0);}}//获取当前计数值publicintgetcount(){returnthis.count;}//获取当前操作次数publicintgettimes(){returnthis.times;}//判断当前count是否超过MaxpublicbooleanoverMax(){if(Math.abs(this.count)<this.Max)returnfalse;returntrue;}//判断当前操作次数是否超过最大次数publicbooleanoverN(){if(this.times <this.N)returnfalse;returntrue;}//绘制点publicvoiddraw(){StdDraw.point(this.times,this.count);}}publicstaticvoidmain(String[] args)throwsException{int n =200;int max =100;VisualCounter counter =newVisualCounter(n, max);StdDraw.setPenRadius(0.2);for(int i =0; i <120;i++){
counter.increment();
counter.draw();}}}