2007/01/01 | Java.study.Counter
类别(STUDY) | 评论(0) | 阅读(34) | 发表于 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

0

评论Comments

日志分类
首页[90]
GUITAR[43]
JRUM[4]
PIANO[23]
HEART_ACHES[5]
STUDY[7]
FRAGMENT[8]