public class ArrayStackDemo {public static void main(String[] args) {ArrayStack arrayStack = new ArrayStack(4);Scanner sc = new Scanner(System.in);boolean loop = true;char key = ' ';while (loop) {System.out.println("======栈操作菜单项======");System.out.println("1. s(showList) 打印栈元素");System.out.println("2. a(push) 元素入栈");System.out.println("3. p(pop) 元素出栈");System.out.println("4. e(exit) 程序退出0");System.out.println("请输入你的选择:");key = sc.next().charAt(0);switch (key) {case 's':case '1':arrayStack.showList();break;case 'a':case '2':System.out.println("请输入你要添加的元素:");int value = sc.nextInt();arrayStack.push(value);break;case 'p':case '3':try {System.out.println("出栈元素为:" + arrayStack.pop());} catch (Exception e) {System.out.println(e.getMessage());}break;case 'e':case '4':sc.close();loop = false;System.out.println("程序退出~");
// System.exit(0);break;default:break;}}}
}//定义一个ArrayStack 表示栈
class ArrayStack {private int maxSize; //栈的大小private int[] stack; //定义一个栈private int top = -1; //定义一个栈顶指针public ArrayStack(int size) {maxSize = size;stack = new int[maxSize];}//栈满public boolean isFull() {return top == maxSize - 1;}//栈空public boolean isEmpty() {return top == -1;}//添加元素public void push(int value) {if (isFull()) {System.out.println("栈满,不能继续添加元素~");return;}stack[++top] = value;}//元素出栈public int pop() {if (isEmpty()) {throw new RuntimeException("栈空,无元素出栈~");}return stack[top--];}//遍历栈元素public void showList() {if (isEmpty()) {System.out.println("栈空,无元素遍历~");return;}for (int i = top; i >= 0; i--) {System.out.printf("元素 %d \n", stack[i]);}}
}