package stack; import java.util.Scanner; public class ArrayStackTest { public static void main(String[] args) { ArrayStack arrayStack = new ArrayStack(4); Scanner scanner = new Scanner(System.in); boolean loop = true; String key = ""; while(loop == true){ System.out.println("向栈加入数据:" + "push"); System.out.println("显示队栈中数据:" + "show"); System.out.println("获取栈顶数据:" + "pop"); System.out.println("退出:" + "exit"); System.out.println("请输入你的选项:"); key = scanner.next(); switch (key){ case "push": System.out.println("请输入一个整数"); int value = scanner.nextInt(); arrayStack.push(value); break; case "show": arrayStack.show(); break; case "pop": try { System.out.println(arrayStack.pop()); } catch (Exception e) { System.out.println(e.getMessage()); } break; case "exit": loop = false; break; default: System.out.println("请输入正确指令"); break; } } System.out.println("程序退出"); } } class ArrayStack{ int maxsize; int[] stack; int top = -1; public ArrayStack(int maxsize) { this.maxsize = maxsize; stack = new int[maxsize]; } public boolean isEmpty(){ return top == -1; } public boolean isFull(){ return top == maxsize - 1; } public void push(int value){ if (isFull()){ System.out.println("栈满"); return; } top++; stack[top] = value; } public int pop(){ if (isEmpty()){ throw new RuntimeException("栈空"); } int value = stack[top]; top--; return value; } public void show(){ if (isEmpty()){ System.out.println("栈空"); return; } for (int i = top; i >=0 ; i--) { System.out.printf("stack[%d]=%d\n",i,stack[i]); } } }