Reputation: 93
I am fairly new to Smalltalk and I'm stuck on how to print elements from a stack. I have two classes, one which creates the stack using OrderedCollection, which works, and a second class (Object subclass). For the second class I have two instance variables name and weight(with set and get methods). I need to make two more methods print and printSpecial. Print output the name and weight to the Transcript on the same line using the get method from name but cannot use the get method from weight. PrintSpecial is similar to print but the weight must be < 100. I have tried doing print and printScpecial but cannot figure it out. Below is what I have so far. Any help would be appreciated.
name: a
name := a
name
^name
print
[ Transcript
show: weight;
show: name;
cr ]
printSpecial
[ weight <= 100 ]
whileTrue: [ Transcript
show: weight;
show: name;
cr ]
Upvotes: 1
Views: 353
Reputation: 14858
Both your print
and printSpecial
methods enclose their bodies in squared brackets. You should remove them. Try:
print
Transcript
show: weight;
show: name;
cr
printSpecial
weight <= 100 ifTrue: [
Transcript
show: weight;
show: name;
cr]
Notice that in printSpecial
I've replaced whileTrue:
with ifTrue:
. The reason is that you don't want to keep printing for ever if the weight
happens to meet the condition.
Another thing I would suggest is to avoid repeating code. So, I would propose this:
printSpecial
weight <= 100 ifTrue: [self print]
This way, if you later decide to improve print
you won't have to copy the improvement to printSpecial
.
Finally, you say you have a collection of these objects. Therefore you should have some way of enumerating them (e.g., via do:
). Thus, if the actual request consisted in printing them all you should implement print
and printSpecial
in the elements' class and then implement the same messages in your Stack
class.
Stack >> print
collection do: [:elem | elem print]
Stack >> printSpecial
collection do: [:elem | elem printSpecial]
where I'm assuming that the instance variable that holds your elements is named collection
.
Even better. You could implement do:
in your Stack
class and then use self do:
instead of collection do:
as I did above. Something on the lines of
Stack >> do: aBlock
collection do: aBlock
and then
Stack >> print
self do: [:elem | elem print]
Stack >> printSpecial
self do: [:elem | elem printSpecial]
Upvotes: 4