Search code examples
javastackpalindrome

Adding char from string to stack


I am trying to add the chars from a string in a textbox into my Stack,

here is my code so far:

String s = txtString.getText();
Stack myStack = new LinkedStack();

  for (int i = 1; i <= s.length(); i++)
{
    while(i<=s.length())
        {
         char c = s.charAt(i);
        myStack.push(c); 
        }
       System.out.print("The stack is:\n"+ myStack);
}

My push and pop method from LinkedStack

public void push(Object item){
  top = new ListNode(item, top); 
}

public void pop(){
  if(isEmpty())
    throw new StackUnderflowException("Nothing removed-stack is empty");
  else
   top = top.getNext();
}

getnext() method comes from another package called listnodes

public ListNode getNext() {
    return nextNode; // get next node
} // end method getNext

when I change the print to + c, all the chars from my string prints, but when it is myStack it now gives me a string out of index range error.

Does anybody know what I am missing?


Solution

  • LinkedStack.toString is not terminating. You're probably missing a base case there. Add a proper base case to it, and/or make sure your stack doesn't end up cyclic due to a bug in push or pop, and your print should work fine.

    Your push implementation looks ok, pop doesn't assign top, so is definitely broken.