开发者

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?


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜