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;
}
}
}
}
Algs4-1.2.10編寫一個類VisualCounter