2

我正在尝试将文本框中字符串中的字符添加到我的堆栈中,

到目前为止,这是我的代码:

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

我来自 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() 方法来自另一个名为 listnodes 的包

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

当我将打印更改为 + c 时,我的字符串中的所有字符都会打印出来,但是当它是 myStack 时,它现在给了我一个超出索引范围错误的字符串。

有人知道我错过了什么吗?

4

3 回答 3

2

LinkedStack.toString没有终止。你可能在那里错过了一个基本案例。为其添加适当的基本情况,和/或确保您的堆栈不会由于 push 或 pop 中的错误而结束循环,并且您的打印应该可以正常工作。

你的push实现看起来不错,pop没有分配top,所以肯定坏了。

于 2011-09-20T00:08:54.867 回答
2
String a = "String";
Stack<Character> stack = new Stack<>();
a.chars().forEach(c -> stack.push((char)c));
于 2019-02-27T23:42:36.153 回答
0
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);
}

你的 for 循环应该从 0 开始并且小于长度。另一个错误是 while 循环无限运行,因为只要字符串的长度不为空,1 将始终小于长度或任何数字。因此,在您的情况下,我只需删除 while 语句并在 for 循环中完成所有操作,毕竟您的 for 循环只会运行与字符串中的项目一样多的次数。

固定版本,可以做你想做的事。

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

          System.out.print("The stack is:\n"+ myStack);
    }
于 2017-04-14T23:22:11.390 回答