maria maria - 3 years ago 121
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)){

if(ch == '-'){

Answer Source

Override the toString of MyStack:

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

Now you can do


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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download