Jebathon
Jebathon

Reputation: 4561

Creating a method that prints while emptying the contents of a Stack

Given the class: 'AStack'

Object subclass: #AStack
    instanceVariableNames: 'elements'
...

It contains an OrderedCollection Object that holds it's 'element objects'

initialize 
super initialize.
elements := OrderedCollection new

It's member classes push and pop, respectively:

push: anObject 
self elements addFirst: anObject 

pop
^self elements removeFirst 

I am trying to write a print method that uses timesRepeat to print the contents of the stack as well as empty it simultaneously. It calls the child class print method for each 'element' (print ^self name) and outputs it on the screen using 'Transcript'.

print
self size timesRepeat: [Transcript show: self pop print]

On the other side I have a class called 'SomeRandomObject' who's print method is:

print
Transcript show:self getName; cr

Workspace code:

| o1 o2 stk |

o1 := SomeRandomObject new.
o1 name: 'object1'.

o2 := SomeRandomObject new.
o2 name: 'object2'.

stk := AStack new.
stk push: o1.
stk push: o2.

stk print "prints and emptys stack"

Upon running I get the error:

Error: Instances of AStack are not indexable

How can I fix my code so the print method shows o1 and o2 name while popping them off the stack?

Upvotes: 1

Views: 125

Answers (2)

MartinW
MartinW

Reputation: 5041

You would get the "Instances of AClass are not indexable“ error if you sent at:, at:put: or size to instances of a class that has no indexed instance variables or has not overridden these methods.

So if you send any of these messages to instances of AStack (which has no indexed instance variables), make sure AStack defines the ones you send.

Upvotes: 1

Uko
Uko

Reputation: 13386

I cannot tell you exactly before you give me a full (at least bigger) stack trace, but I expect, that you wont have a #size method defined in your class which should be something like this:

size
  ^ elements size

Upvotes: 2

Related Questions