用数组实现栈

package A;

import java.util.Scanner;

public class JosePhu {
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(3);
boolean loop=true;
Scanner scanner = new Scanner(System.in);
while (loop){
System.out.println("四个关键字:show,push,pop,exit");
System.out.println("请输入你的操作:");
String key=scanner.next();
switch (key){
case "show":
arrayStack.list();
break;
case "push":
System.out.println("请输入你想入栈的数:");
int value=scanner.nextInt();
arrayStack.push(value);
break;
case "pop":
System.out.print("出栈的数是:");
arrayStack.pop();
break;
case "exit":
scanner.close();//优雅的离去(因为它是一个流,所以要关闭)
loop=false;
break;
/*try {
int res=arrayStack.pop();
System.out.println("出栈的顺序是:"+res);
}catch (Exception e){
System.out.println(e.getMessage());
}这是博主写的,我没看懂,以后看,我自认为我自己写的还好一些*/
default:
System.out.println("输入格式有误,请重新输入");
break;
}
}
System.out.println("已退出程序");
}
}

package A;

public class ArrayStack {
private int maxSize;
private int[] stack;
private int top=-1;

public ArrayStack(int maxSize){//构造器
this.maxSize=maxSize;
stack=new int[this.maxSize];
}

public boolean isFull(){
return top==maxSize-1;//按数组0开始,那种思路来考虑的
}
public boolean isEmpty(){
return top==-1;
}
public void push(int value){
if (isFull()){
System.out.println("本栈已满,");
return;
}else {
top++;
stack[top]=value;
}
}
public int pop(){
if (isEmpty()){//莫非他会出现数组是空的这种异常?
//没有嘞,假如用这行的话,它会在控制台出现这句话的异常,并且结束程序
//throw new RuntimeException("栈空!");
System.out.println("本栈已为空,");
return 0;
}else {
int value=stack[top];
top--;
System.out.println(value);
return value;
}
}
public void list(){
if (isEmpty()){
System.out.println("栈是空的。");
return;
}else {
for (int i=top;i>=0;i--){
System.out.println("stack["+i+"]="+stack[i]);
}
}
}

}
posted @ 2021-07-26 00:16  朱在春  阅读(69)  评论(0编辑  收藏  举报