1 package mycodes.exception.test2;
2 /*
3 * 这个类是用数组模拟栈内存(方式1:控制下标),通过异常处理提示用户栈满栈空
4 */
5 public class Stack1 {
6 private String[] arr;
7 private int p = 0;
8
9 public Stack1(int len) {
10 arr = new String[len];
11 }
12
13 // 压栈
14 public void push(String str) throws StackException {
15 // 不要在这里写循环
16 if (p < arr.length)
17 arr[p++] = str;
18 else {
19 throw new StackException("栈已满,无法继续压栈");
20 }
21 }
22
23 // 弹栈
24 public String pop() throws StackException {
25 // 不要在这里写循环
26 if (p > 0) {
27 String str = arr[--p];
28 arr[p] = null;
29 return str;
30 } else
31 throw new StackException("栈空,无法弹栈");
32 }
33 }
1 package mycodes.exception.test2;
2
3 public class StackException extends Exception {
4
5 public StackException(){}
6 public StackException(String msg){
7 super(msg);
8 }
9 public StackException(String msg,Throwable e){
10 super(msg,e);
11 }
12 }
1 package mycodes.exception.test2;
2 /*
3 * 本类用于测试 通过数组模拟栈内存的类 Stack1
4 */
5 public class TestStack12 {
6
7 /**
8 * @param args
9 */
10 public static void main(String[] args) {
11 // TODO Auto-generated method stub
12 //Stack s = new Stack(10);
13 Stack1 s = new Stack1(10);
14 //压栈
15 try {
16 for(int i = 1;i<9;i++){
17 s.push("abc"+i);
18 }
19 } catch (StackException e) {
20 e.printStackTrace();
21 }
22 // 弹栈
23 try {
24 for(int i = 0;i<14;i++){
25 String str =s.pop();
26 System.out.println("弹栈-->" +str );
27 }
28 } catch (StackException e) {
29 e.printStackTrace();
30 }
31 }
32 }