自写异常类:
/**
-
自写栈空异常类
*/
public class EmptyException extends Exception {
public EmptyException() {
}
public EmptyException(String message) {
super(message);
}
}
数组模拟栈:
import java.util.Arrays;
/**
-
数组模拟栈——后进先出表
*/
public class Stack {
private int top = -1 ;//栈顶前一个位置
private int maxSize;
private int[] arr;public Stack(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
}public void setArr(int[] arr) {
this.arr = arr;
}public boolean isFull(){//判断栈满
return topmaxSize - 1;//返回top等于maxSize-1
}
public boolean isEmpty() throws EmptyException {//判断栈空
if(top-1) {//如果top等于-1
throw new EmptyException(“栈空异常!”);
}
else return false;
}
public void push(int count){//入栈if(!isFull()){ top++; arr[top]=count; }else System.out.println("栈满,不能再添加元素");
}
public void pop() throws EmptyException {//出栈if (!isEmpty()) { System.out.println("出栈元素:"+arr[top]); arr[top] = 0; top--; }
}
public void peek() throws EmptyException {//显示栈顶元素
if(!isEmpty()) {
System.out.println(“栈顶元素:” + arr[top]);
}
}
public void show() throws EmptyException {
if (!isEmpty()) {
int temp = top;//临时辅助指针
for (int i = temp; i >= 0; i–) {
System.out.printf(“stack[%d] = %d\n”, i, arr[i]);
}
}
}
}
测试类:
/**
-
测试类
*/
public class Test {
public static void main(String[] args) throws EmptyException {
Stack stack = new Stack(10);
while(true){
System.out.println(“请输入指令:in(入栈)/out(出栈)/check(查栈顶元素)/show(显示栈)/exit(退出)/”);
Scanner sca= new Scanner(System.in);
String str = sca.next();
if(str.equals(“in”)){
System.out.println(“请输入入栈元素:”);
int count = sca.nextInt();
stack.push(count);
}else if(str.equalsIgnoreCase(“out”)){
try {
stack.pop();
}catch(Exception e){
e.printStackTrace();
}
}else if(str.equalsIgnoreCase(“check”)){
try {
stack.peek();
} catch (EmptyException e) {
e.printStackTrace();
}
}else if(str.equalsIgnoreCase(“exit”)){
System.out.println(“再见!”);
break;
}else if(str.equalsIgnoreCase(“show”)){
stack.show();
}
else System.out.println(“输入有误,请重输”);}
}
}