我正在编写一个程序来使用堆栈数据结构反转单词。它应该工作的方式是我输入一个字符串,将字符串的每个字符插入一个堆栈对象中,然后我会将每个对象从堆栈中弹出并打印它们。该单词将与原始输入的顺序相反,因为这正是堆栈的工作方式。
我不断得到索引越界异常;调试让我怀疑它与 Stack 类中的初始数组初始化有关,但它也可能与 push() 函数有关。
这是整个代码:
public class Stack // object to emulate stack data structure
{
private int stackMaxSize;
private char stackArray[];
private int currentSize;
public Stack() // if initialized without any parameters
{
this(100);
}
public Stack(int maxSize) // if initialized with parameter
{
maxSize = stackMaxSize;
stackArray = new char[stackMaxSize];
currentSize = -1;
}
public void push(char c) //pushes new character into stack
{
stackArray[++currentSize] = c;
}
public char pop() //pops character out of stack
{
return stackArray[currentSize--];
}
public char peek() // returns character on top of stack
{
return stackArray[currentSize];
}
public boolean isEmpty() // returns whether stack is empty or not
{
return (currentSize < 0);
}
}
这是主要的:
import java.util.Scanner;
public class ReverseWord
{
public static void main(String[] args)
{
Stack wordStack = new Stack(100); // default size is 100
System.out.print("Enter the word to be reversed: ");
String word = getString();
for (byte i = 0; i <= word.length(); i++) // inserts word into stack char by char
{
wordStack.push(word.charAt(i));
}
System.out.print(wordStack.pop());
}
static String getString()
{
Scanner input = new Scanner(System.in);
String s = input.nextLine();
return s;
}
}
非常感谢!
仲量联行