2009年6月24日 星期三

Homework 7 3/30 Counter

Define a class called Counter whose objects count things. An object of this class records a count that is a nonnegative integer. Include methods to set the counter to 0, to increase the count by 1, and to decrease the count by 1. Include an accessor method that returns the current count value and a method that outputs the count to the screen. Write a program to test

counter.reset();
counter.inc();
counter.inc();
counter.dec();
counter.output();


程式畫面 Class



class定義中有一個私變數count,負責存放計算的非負整數。
另外還有應題目要求設置了4個public methods
其中在遞減1的部分加了限制,當count為零之後即不再作遞減的動作,以符合非負整數的條件。

程式畫面 Demo code



使用switch提供選擇想要的功能,照題目要求,程式輸出如下。


程式畫面 輸出

沒有留言:

張貼留言