スタックを使用するプログラム用に作成した 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);
}
}
どんな助けや指示もいただければ幸いです。