Java.study.Counter

      STUDY 2007-1-1 11:19

· 实验

·作用:计数器,实现每次加一或减一运算

·代码:
public class Counter {
//post:increase or decrease cnt by 1
private int cnt;
public Counter(){
 cnt=0;
}//end default constructor
public void inc(){
 ++cnt;
}//end inc 
public void dec(){
 if(cnt>0)
 --cnt;
 else
  System.out.println("error");
}//end dec
public int getCnt(){
 return cnt;
}//end getCnt
public void print(){
 System.out.println("The counter is "+cnt);
}//end toString
public static void main(String[] args){
 Counter cntr = new Counter();
 for(int i=10;i>0;--i){
  cntr.inc();
  cntr.print();
 }
 for(int i=15;i>0;--i){
  cntr.dec();
  cntr.print();
 }   
}
}

·运行结果

The counter is 1
The counter is 2
The counter is 3
The counter is 4
The counter is 5
The counter is 6
The counter is 7
The counter is 8
The counter is 9
The counter is 10
The counter is 9
The counter is 8
The counter is 7
The counter is 6
The counter is 5
The counter is 4
The counter is 3
The counter is 2
The counter is 1
The counter is 0
error
The counter is 0
error
The counter is 0
error
The counter is 0
error
The counter is 0
error
The counter is 0

标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commenttime}{commentauthor}

{CommentUrl}
{commentcontent}