Norm Radder wrote:What happened to the original OP?
It looks like Houssam El has stolen this thread for his own code.
Should Houssam El's code be moved to its own thread so that the original OP can work on his problem?
Jesse Silverman wrote:Houssam, do you see two problems with that tho?
1. What if we attempt to push on to the stack when it is full? There is no way to even check that in the new code, the user would have to remember the size in their own code.
2. What if we attempt to pop from the stack when it is empty? That can still be prevented by calling isEmpty() first, but it is easier to remember 0 than an arbitrary size.
By adjusting things, we can get an API that will be self-aware of full as well as empty conditions, and to display only what is currently on the stack.
Carey Brown wrote:pop() is wrong.
Jesse Silverman wrote:Hi Again, Houssam:
Even before that, the current output would look the same whether we had not used the stack at all yet, or if we had pushed five 0 elements on to it and it was full.
We are using an array internally, yes, but we are trying to provide a class that will have normal stack-like behavior, except probably for a fixed maximum size.
Up to that limit, pushing one on, popping one off, displaying the contents, etc. should behave similarly as for a general stack class, which means showing everything that has been pushed on to it but nothing more.
Carey Brown wrote:With your code, let's say we have a size of 5. To start with, if we displayStack() we get
0 0 0 0 0
Now push '1' and display
1 0 0 0 0
Now push 2 through 5 and display
1 2 3 4 5
Now pop and pop and display
1 2 3 4 5
See, '4' and '5' will not be zero?
Carey Brown wrote:You won't necessarily get zeros (0) because as the stack grows and shrinks the old values are left behind.
Carey Brown wrote:Agreed, but if you've only pushed 1 why would you print more?
A binary search implies that the array is in sorted order which is not the case. And why would you print 65,000 if only one number has been pushed on the stack?
"toString()" is implemented as to whatever makes sense for the particular class to present to the user. You can see similar implementations in Arrays and Lists.
If maxSize is 65,000 are you sure you want to print that many?
Why not implement this as a toString() method?
Carey Brown wrote:@Houssam, I'm going to move this to the Beginner forum, and just a heads up, there we try not to give complete answers but to help the original poster to come up with the answer on their own through hints, explanations, and code snippets.
Also, in the code you posted there are a couple of bugs.