maria maria - 1 month ago 5
Java Question

how to print a self implemented stack?

I'm using a self implemented stack to delete and add characters in order to get a final result (I'm kind of decoding a string).

Example: The input 'hello-' has to give 'hell'. The '-' deletes the character before it.

Current output - 'hellol'

The only requirement is that I have to use a self implemented stack. Do you guys have any suggestions? I appreciate your help!

//this is my code for the stack
public class MyStack{
static int maxSize;
static char[] stackArray;
static int top;

public MyStack(int s) {
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}

public boolean empty() {
return (top == -1);
}

public void push(char item) {
stackArray[++top] = item;

}

public char peek() {
return stackArray[top];
}

public char pop() {
return stackArray[top--];
}
}

//this is in my main:
for (char ch : password.toCharArray()){ //password is the input(hello-)
if(Character.isLetter(ch) || Character.isDigit(ch)){
theStack.push(ch);
System.out.println(theStack.peek());
}

if(ch == '-'){
theStack.pop();
System.out.println(theStack.peek());
}
}

Answer

Override the toString of MyStack:

@Override
public String toString() {
    return "MyStack: " + new String(stackArray, 0, top + 1):
}

Now you can do

System.out.println(theStack);

The fields should not be static. With static the fields exist once for the entire class. Without the fields exist for every stack object.

private int maxSize;
private char[] stackArray;
private int top;