我为使用堆栈的程序创建的 2 个类有问题。我遇到的第一个问题是,当我尝试运行程序时出现运行时错误。
这是一件很难问的事情,因为它做了几件事。它要求用户输入以将数字添加到堆栈并检查堆栈是否已满或为空。我也可能需要帮助来复制数组。
线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:在 Lab15.main(Lab15.java:38) 的 IntegerStack.push(IntegerStack.java:24) 处 -1
这是运行程序的主类。
import java.util.Scanner;
public class Lab15 {
public static void main(String[] args)
{
System.out.println("***** Playing with an Integer Stack *****");
final int SIZE = 5;
IntegerStack myStack = new IntegerStack(SIZE);
Scanner scan = new Scanner(System.in);
//Pushing integers onto the stack
System.out.println("Please enter an integer to push onto the stack - OR - 'q' to Quit");
while(scan.hasNextInt())
{
int i = scan.nextInt();
myStack.push(i);
System.out.println("Pushed "+ i);
}
//Pop a couple of entries from the stack
System.out.println("Lets pop 2 elements from the stack");
int count = 0;
while(!myStack.isEmpty() && count<2)
{
System.out.println("Popped "+myStack.pop());
count++;
}
scan.next(); //Clearing the Scanner to get it ready for further input.
//Push a few more integers onto the stack
System.out.println("Push in a few more elements - OR - enter q to quit");
while(scan.hasNextInt())
{
int i = scan.nextInt();
myStack.push(i);
System.out.println("Pushed "+ i);
}
System.out.println("\nThe final contentes of the stack are:");
while(!myStack.isEmpty())
{
System.out.println("Popped "+myStack.pop());
}
}
}
这是将数字添加到堆栈的类,这就是问题所在。这是我可能需要帮助复制数组的地方。在最后。
import java.util.Arrays;
public class IntegerStack
{
private int stack [];
private int top;
public IntegerStack(int SIZE)
{
stack = new int [SIZE];
top = -1;
}
public void push(int i)
{
if (top == stack.length)
{
extendStack();
}
stack[top]= i;
top++;
}
public int pop()
{
top --;
return stack[top];
}
public int peek()
{
return stack[top];
}
public boolean isEmpty()
{
if ( top == -1);
{
return true;
}
}
private void extendStack()
{
int [] copy = Arrays.copyOf(stack, stack.length);
}
}
任何帮助或方向将不胜感激。