编辑代码

import java.util.Scanner;

class Main {
	public static void main(String[] args) {
        //实现栈的思路分析
        //使用数组来模拟栈,定义一个变量top来表示栈顶,初始化为-1
        //入栈:当有数据加入到栈时,top++,stack[top] = data;
        //出栈:需要一个临时变量value,int value = stack[top];top--,return value;
        ArrayStack stack = new ArrayStack(4);
        Scanner sc = new Scanner(System.in);
        String key = "";
        boolean loop = true;
        while(loop){
            System.out.println("show");
            System.out.println("exit");
            System.out.println("push");
            System.out.println("pop");
            System.out.print("Enter your choose:");
            key = sc.nextLine();
            switch(key){
                case "show":
                    stack.list();
                    break;
                case "exit":
                    sc.close();
                    loop = false;
                    break;
                case "push":
                    System.out.println("please enter add number element:");
                    int value = sc.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    try{
                        int res = stack.pop();
                        System.out.println("pop value is:" + res);  
                    }catch(Exception e){
                        throw new RuntimeException(e);
                    }
                    break;
                default:
                    System.out.println("please reenter the String");
                    break;
            }
        }
        System.out.println("System is exited");
	}
}

//定义一个类,表示栈结构
class ArrayStack{
    private int maxSize;//栈大小
    private int[] stack;//数组,将数组模拟栈,数据就放在该数组中
    private int top = -1;//top为栈顶

    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        stack = new int[this.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;
        }
        top++;
        stack[top] = value;//赋值
    }

    //出栈,将栈顶的数据取出
    public int pop(){
        if(isEmpty()){//判断栈是否为空
            throw new RuntimeException("栈空!");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //遍历栈,遍历时需要从栈顶开始显示数据
    public void list(){
        if(isEmpty()){
            System.out.println("栈空!");
        }
        for(int i = top;i >= 0;i--){
            System.out.print("stack[" + i + "]:" + stack[i] + "\t");
        }
        System.out.println();
    }
}