2007年11月30日 星期五

Lab 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();

Step1. Writing Methods

插曲: value++ 、++value or value--、 --value 會有不同的結果!!


















(1) return value++ ← 先回傳直,再對 value 做 +1 的動作。
(2) return ++value ← 先對 value 做 +1 的動作,然後再回傳。 (--value) 相同
(3)可能有人會問,同樣 value 都有做 +1 或 -1 的動作,為什麼後 ++ 的最後運算完會沒有值呢?

Ans: 因為在 method 內宣告的變數為區域變數 ( 其實 Mr. Java 說: 「我沒有全域變數(global variable) !!」)。Hence,每執行完一次 method 其變數會被釋放回記憶體,換句話說,沒有記憶的能力,所以最後的 value 會為 0。當然, 先 ++ 的 value 早在它被釋放為記憶體前,就先回傳給 number 了 。

Step2. testing


















Step3.After testing...........

沒有留言: