用堆栈反转一个单词

时间:2013-03-08 19:57:50

标签: java

我是新来的,也是编程的。我正在尝试单独学习其他主题,因为当我有一个问题时,我的导师没有足够的帮助,所以在这里。我希望用一个通用Stack反转一个单词。

我的pop,push,isEmpty和peek方法工作(我在我尝试之前用一个更简单的程序测试它们。)并且输出似乎给了我反转的字符char by char但是在每个char之前总是给我一个null!

我的问题是: 为什么会这样?即使我有一个expandCapacity方法在容量为9时工作,但是当输入超过限制时它不适用。


这是我的代码

package Stack;

import java.util.Scanner;

public class ReverseDriver<T> {
    private static String out;
    private static String in;

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter your sentence: ");
        in = input.nextLine();
        int size = in.length();

        ArrayStack<Character> revStack = new ArrayStack<>(size);

        for (int i = 0; i < in.length(); i++) {

            char u = in.charAt(i);
            revStack.Push(u);
            if (in.length() > 9) {

                revStack.expandCapacity();

            }
        }

        while (!revStack.IsEmpty()) {
            char u = revStack.Pop();
            out = out + u;
            System.out.flush();
            System.out.print(out);

        }

    }
}

这是输出

run:
Enter a word: 
word
nullr
nullro
nullrow
Exception in thread "main" java.lang.NullPointerException
    at Stack.ReverseDriver.main(ReverseDriver.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)

编辑:这是我说的工作方法。

@Override
public void Push ( T element)
   {
     if (count == stack.length){
         expandCapacity();
     }
      stack[++count] = element;


       //System.out.println(count);
   }



  @Override
   public String toString()
   {
      String result = "<top of stack>\n";

      for (int index=count-1; index >= 0; index--){
         result += stack[index] + "\n";
      }
      return result + "<bottom of stack>";
   }





         @Override
    public boolean IsEmpty()
    { //Checks if array is empty
        if(count == 0){
        System.out.println("Nothing");
        }

         return count == 0;


    }


 public  T Pop() 
      {

             T output; 

         output =  (stack[count - 1]);
         count--;


         return(output);

      }



 @Override
    public T Peek()
      {
          //looks at the object at the top of this stack without removing it
     //from the stack.

          if(stack.length == 0){
         // {
      System.out.println("Cant peek a ghost");

          }

         return(stack[--count]);

      }
         // else
         // {
     // System.out.println( stack[count-1]);

         // }

     // }

      @Override
    public int Size()
    {
        //Sets the size of this vector
        if(stack.length == 0){
            System.out.println("Nothing inside");
        }

       System.out.println("The array's size is : " + count);
        return count;


    }



}

3 个答案:

答案 0 :(得分:6)

private static String out;

out中的值为空。

out = out + u;
// This is null = null + u;

因此输出开头为空。

您只需创建一个新的String对象即可为out提供初始值:

 private static String out = "";

答案 1 :(得分:1)

我不确定为什么你需要ExpandCapacity位,这也有效:

public static void main(String[] args)
    {       

    String word ="reverse please";      
    Stack<Character> chStack = new Stack<Character>();      
    for (int i = 0; i < word.length(); i ++)
    {       
        chStack.push(word.charAt(i));       
    }

    String out = "";
    while (chStack.size() != 0)
    {
        out += chStack.pop();
        System.out.println(out);

    }               
}

答案 2 :(得分:1)

有一些注意事项:

  • 你不是在写一个通用类,所以放弃。
  • 尽可能保持迭代。
  • 尽可能尝试使用Java标准类,在本例中为Stack而不是ArrayStack。
  • 您不需要调整堆栈大小,它会在您放入更多数据时动态处理其大小。
  • 一旦完成,就应该在每个步骤中创建一次字符串。
  • 使用+追加字符串效率非常低。使用StringBuilder。
  • 使用它们使代码可读的方法。

下面是代码:

import java.util.Scanner; 
import java.util.Stack;

public class ReverseDriver {
  public static String reverse(String string) {
    Stack<Character> revStack = new Stack<Character>();
    for (char c : string.toCharArray()) {
      revStack.push(c);
    }
    StringBuilder builder = new StringBuilder();
    while(!revStack.isEmpty()){
      builder.append(revStack.pop());
    }
    return builder.toString();
  }

  public static void main(String[]args){
    Scanner input = new Scanner(System.in);
    System.out.println("Enter your sentence: ");
    String in = input.nextLine();
    System.out.println(reverse(in));
  }
}