我正在实现StackArray,这是我第一次这样做。该程序应该将5个元素压入堆栈,我要查找的输出是[a,b,c,d,e],然后它将弹出列表的头并再次打印,直到列表为空。但是,我的输出是[a,b,c,d]。它完全忽略了最后一个元素。我相信我的push和pop方法需要稍做修改。

import java.util.NoSuchElementException;

public class StackArray //implements Stack interface
{
   private Object[] item; // The array where elements are stored
   private int top = 0;  // The index of the first empty location in the stack
   private int size = 2;  // The current number of item locations in the stack
   private Object[] temp = new Object[size];
   /**
      Constructs an empty stack.
   */
   public StackArray()
   {
      item = new Object[size];
   }

   public void push(Object element)
   {
      if (top == item.length)
      {
         size = item.length * 2;
         Object[] newItem = new Object[size];
         for (int i = 0; i < item.length; i++)
         {
            newItem[i] = item[i];
         }
         item = newItem;
      }
      item[top++] = element;
   }
   public Object pop()
   {
      if (isEmpty())
      {
         throw new NoSuchElementException();
      }
      return item[--top];
   }
   public boolean isEmpty()
   {
      return top == 0;
   }

   public String toString()
   {
      if (top == 0) { return "[]"; }
      String temp = "[" + item[0];
      int i = 1;
      while (i < top)
      {
         temp = temp + ", " + item[i];
         i = i + 1;
      }
      temp = temp + "]";
      return temp;
   }
}


这是我的跑步程序:

public class StackArrayRunner
{
   public static void main(String[] args)
   {
      StackArray sa = new StackArray();
      sa.push("a");
      sa.push("b");
      sa.push("c");
      sa.push("d");
      sa.push("e");
      System.out.println(sa);
      System.out.println(sa.pop());
      System.out.println(sa);
      System.out.println(sa.pop());
      System.out.println(sa);
      System.out.println(sa.pop());
      System.out.println(sa);
      System.out.println(sa.pop());
      System.out.println(sa);
      System.out.println(sa.pop());
      System.out.println(sa);
      System.out.println(sa.pop());
   }
}


输出应为:
[a,b,c,d,e]
Ë
[A B C D]
d
[a,b,c]
C
[a,b]
b
[一种]
一种

谢谢!
好,关于异常的快速问题。我的输出现在是正确的,但最后会抛出No such element异常。这正常吗?那应该发生吗?这是新的输出:

[a, b, c, d, e]
e
[a, b, c, d]
d
[a, b, c]
c
[a, b]
b
[a]
a
[]
Exception in thread "main" java.util.NoSuchElementException
    at StackArray.pop(StackArray.java:35)
    at StackArrayRunner.main(StackArrayRunner.java:22)

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

最佳答案

您将获得预期的结果:您正在推动五个元素,并进行六个pop()调用!

前五个弹出一个元素并将其返回(正确);最后一个打印出空堆栈([]),然后尝试到pop(),这给您带来了问题。它会抛出一个NoSuchElementException,因为当您尝试从一个空堆栈中弹出时,代码就是这样做的。

这看起来像是对我进行良好单元测试的基础:)

10-05 21:10
查看更多