如何将字符串中的字符放入基于数组的ADT堆栈版本中

时间:2011-03-23 21:27:38

标签: java adt stack

所以对于我的任务,我需要使用基于数组的ADT堆栈版本来创建一个名为myStack的堆栈。然后我需要创建一个名为str的字符串变量并将其分配给字符串“abcdefg”并访问字符串中的字符并将每个字符推入堆栈,从第一个开始。在所有字符都在堆栈中之后,我需要弹出并在一行上显示每个字符。这是我正在使用的:

public class StackArrayBased
{
  private static final int MAX_STACK = 7 ;
  private Object items [ ] ;
  private int top ;

  public StackArrayBased ( )
  {
    items = new Object [ MAX_STACK ] ;
    top = -1 ;
  }

  public boolean isEmpty ( )
  {
    return top < 0 ;
  }

  public boolean isFull ( )
  {
    return top == MAX_STACK - 1 ;
  }

  public void push ( Object newItem ) throws StackException
  {
    if ( ! isFull ( ) )
      items [ ++ top ] = newItem ;
    else
      throw new StackException ( "StackException on push: stack is full" ) ;
  }

  public void popAll ( )
  {
    items = new Object [ MAX_STACK ] ;
    top = -1 ;
  }

  public Object pop ( ) throws StackException
  {
    if ( ! isEmpty ( ) )
      return items [ top -- ] ;
    else
      throw new StackException ( "StackException on pop: stack is empty" ) ;
  }

  public Object peek ( ) throws StackException
  {
    if ( ! isEmpty ( ) )
      return items [ top ] ;
    else
      throw new StackException ( "StackException on peek: stack is empty" ) ;
  }
}

以及:

public class StackException extends RuntimeException
{
  public StackException ( String s )
  {
    super ( s ) ;
  }
}

这是我到目前为止所做的,但是我无法理解为什么我得到异常并且它运行不正确:

public class StackArrayBasedTester
{
  public static void main ( String [ ] args )
  {
    String str = "abcdefg" ;
    StackArrayBased myStack = new StackArrayBased ( ) ;
    Integer i = 1 ;
    Character c ;
    for ( i = 1 ; i <= 7 ; i++ )
      if ( ! myStack.isFull ( ) )
        myStack.push ( c = str.charAt ( i ) ) ;
    while ( ! myStack.isEmpty ( ) )
      System.out.print( " "+myStack.pop ( ) ) ;
  }
}

还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

你得到什么样的例外?

charAt从0开始计数。执行str.charAt(7)时,您将获得IndexOutOfBoundsException。

此外,如果您想要修改i < str.length()保留其他值,最好循环str