//Stack.java
import java.util.Scanner;
class Stack{
private int[] st;
private int pt;
public Stack(int len){
st=new int[len];
}
public void put(int x)throws ArrayIndexOutOfBoundsException{
st[pt++]=x;
}
public int pop()throws ArrayIndexOutOfBoundsException{
return st[--pt];
}
}
//StackTest.java
import java.util.Scanner;
public class StackTest{
private static Scanner sc=new Scanner(System.in);
private static int menu(){
System.out.println("1.入栈");
System.out.println("2.出栈");
System.out.println("3.退出程序");
return sc.nextInt();
}
public static void main(String[] args){
boolean go=true;
System.out.println("请输入一个整数,初始化堆栈的容量:");
int size=sc.nextInt();
try{
Stack s=new Stack(size);
while(go){
int option=menu();
switch(option){
case 1:
System.out.println("请输入一个整数:");
int num=sc.nextInt();
s.put(num);
break;
case 2:
System.out.println(s.pop());
break;
case 3:
go=false;
break;
default:
System.out.println("输入有误");
}
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("堆栈溢出");
}
}
}