测试代码:
public class Test13 {
public static void main(String[] args) {
// 创建自定义异常类的实例,并不抛出,测试自定义异常类
/*MyStackOperatorException e = new MyStackOperatorException("栈操作有误");
String msg = e.getMessage();
System.out.println(msg); // 栈操作有误
e.printStackTrace(); // exception.MyStackOperatorException: 栈操作有误
// at exception.Test13.main(Test13.java:23)*/
// 自定义异常完成栈满压栈异常,栈空出栈异常
try {
MyStack stack = new MyStack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
// 已压栈5次,下面必出异常
stack.push(6);
} catch (MyStackOperatorException e) {
e.printStackTrace();
}
}
}
// 自定义异常类
class MyStackOperatorException extends Exception {
public MyStackOperatorException() {
}
public MyStackOperatorException(String s) {
super(s);
}
}
// 自定义栈,能存储任意引用类型
class MyStack {
//栈数组
private Object[] elements;
//栈长度
private int length;
//栈针
private int index;
//外部只能读取 栈的大小 和 栈针的位置
public int getLength() {
return length;
}
public int getIndex() {
return index;
}
//只给一个参数的构造方法,要求确定栈数组的大小
public MyStack(int length) throws MyStackOperatorException {
//假设栈的长度不能超过100
if (length <= 0 || length >= 100){
throw new MyStackOperatorException("栈长度不合法,创建失败");
}
this.length = length;
this.index = 0;
elements = new Object[length];
System.out.println("成功初始化长度为" + length + "的栈");
}
//压栈
void push(Object obj) throws MyStackOperatorException{
if (index == length) {
throw new MyStackOperatorException("栈已存满,压栈失败");
}
elements[index] = obj;
index++;
System.out.println("压栈成功,栈中已存储" + index + "个数据");
}
//出栈
Object pop() throws MyStackOperatorException {
if (index == 0) {
throw new MyStackOperatorException("栈是空的,出栈失败");
}
index--;
System.out.println("出栈成功,栈中剩余" + index + "个数据");
return elements[index];
}
}