Reputation: 9
I'm a little confused on how classes, constructors, and stacks work. I'm trying to create an array with a default size of 5. Then, I have to set the array size by using a constructor. Then, I have to write methods to push and pop values in the array. This is what I have so far
public class createStack{
double [] array = new double[5];
private int top = 0;
public createStack(double[] array){
this.array = array;
}
public void push(double[] array){
if(top >= array.length){
System.out.println("Stack is full");
}
top++;
}
}
Am I doing this correctly? Also, how would I write methods for push and pop? I understand how the methods work, but I'm really confused on where to go with them.
Upvotes: 0
Views: 76
Reputation: 16419
There are a number of problems here:
DoubleStack
not createStack
.top
are unclear. Does it point to the current top of the stack, or the next slot that will be used? It sounds like the former, but since the stack starts out empty, top = 0
can't point to the current top, so it appears to be the latter.push
to take an array as a parameter. It should take the single double
value to push onto the stack.push
doesn't do anything with the backing array in the field, it only looks at the array that was passed to it.Here's an example of something more like I would expect to see:
public class DoubleStack {
private double[] array;
private int top = -1; // top points to the current top of the stack, if any
public DoubleStack() {
array = new double[5];
// note: this could be done with an initializer and this constructor could be omitted
}
public void push(double value) {
if (top >= array.length - 1) {
throw new IllegalStateException("Stack Overflow");
}
++top;
array[top] = value;
// note: the previous two lines could be combined; keeping it simple
}
public double pop() {
if (top < 0) {
throw new NoSuchElementException("Stack Empty");
}
double value = array[top];
--top;
return value;
}
}
Possible changes would be to have a constructor that took a size as a parameter and created an array of the desired size instead of the default of 5; or using an ArrayList<Double>
as a backing store for the stack so that the size would not be fixed.
Upvotes: 1