Peerkon
Peerkon

Reputation: 33

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?

Upvotes: 2

Views: 12785

Answers (3)

Fernando Escalona
Fernando Escalona

Reputation: 41

String a = "String";
Stack<Character> stack = new Stack<>();
a.chars().forEach(c -> stack.push((char)c));

Upvotes: 3

PvMDarkar69
PvMDarkar69

Reputation: 1

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);
}

Your for loop should start at 0 and be less than the length. Another error is that the while loop runs infinitely since 1 will always be less than the length or any number for that matter as long as the length of the string is not empty. So in your case I would simply remove the while statement and just do it all in the for loop, after all your for loop will only run as many times as there are items in your string.

Fixed version that does what you want it to do.

 for (int i = 0; i < s.length(); i++)
    {
          char c = s.charAt(i);
          myStack.push(c); 

          System.out.print("The stack is:\n"+ myStack);
    }

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120506

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.

Upvotes: 2

Related Questions