我是新来的,也是编程新手。我正在尝试单独学习其他主题,因为当我有问题时,我的老师没有足够的帮助,所以就这样吧。我想用通用堆栈反转一个单词。
我的 pop、push、isEmpty 和 peek 方法有效(我用一个更简单的程序对它们进行了测试,然后我在这个程序上尝试了它。)并且输出似乎给我一个 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;
}
}