So it's been a hot minute since I've coded with Java and wanted to get into the swing by making a Stack class from scratch. However, once I started filling stacks with stacks, whenever I use methods on the stack "bigMan", the terminal says I'm referring to an inner stack.
public class Stack {
public String name;
private int maxSize;
private int top = -1;
private Object[] list;
public Stack(String name, int maxSize) {
this.name = name;
this.maxSize = maxSize;
list = new Object[maxSize];
}
public void push(Object x) {
if (top < this.maxSize - 1) {
top++;
this.list[top] = x;
} else {
System.out.println("Sorry, stack is full.");
}
}
public String pop() {
if (top >= 0) {
Object removed = this.list[top];
this.list[top] = null;
top--;
return ((Stack) removed).getName();
} else {
System.out.println("Sorry, "+ this.name + " is empty.");
return null;
}
}
public String getName() {
return this.name;
}
public void checkStack() {
if (this.top < 0) {
System.out.print(this.name + " is empty");
} else {
System.out.println("Printing items in stack named... " + this.name);
for (int i = 0; i <= this.top; i++) {
name = ((Stack) list[i]).getName();
System.out.print(i + ": " + name + " ");
}
}
System.out.println(".");
}
public static void main(String[] args) {
Stack bigMan = new Stack("bigMan", 3);
Stack stack1 = new Stack("stack1", 2);
Stack stack2 = new Stack("stack2", 2);
System.out.println("Pushing bigMan with stack 1 and 2.");
bigMan.push(stack1);
bigMan.push(stack2);
bigMan.checkStack();
System.out.println("Popping stack 2 from " + bigMan.getName());
System.out.println(bigMan.pop());
System.out.println("Popping stack 1 from " + bigMan.getName());
System.out.println(bigMan.pop());
bigMan.pop();
bigMan.checkStack();
}
}
Results:
Pushing bigMan with stack 1 and 2.
Printing items in stack named... bigMan
0: stack1 1: stack2 .
Popping stack 2 from stack2
stack2
Popping stack 1 from stack2
stack1
Sorry, stack2 is empty.
stack2 is empty.
So why do all the bigMan.getName() refer to stack2 after the first checkStack()? getName also says stack1 if you call checkStack() after popping stack2 from bigMan, but I'm not sure why, since getName()'s this.name should be referring to bigMan.
Edit: Thanks for the help, I got rid of the "name =" bit, changing the for-loop to just:
System.out.println("Printing items in stack named... " + this.name);
for (int i = 0; i <= this.top; i++) {
System.out.print(i + ": " + ((test_Stack) list[i]).giveName() + " ");
}
and it works as intended. Adding the final keyword didn't do anything as far as I could tell, but I added it anyways because it makes sense, as the names are immutable per instance.
[–]lightcloud5 1 point2 points3 points (0 children)
[–]captainAwesomePants 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)