1.编写一个EmptyStackException类,它继承Exception类。 2.编写一个FullStackException类,它继承Exception类。捕获该异常时,可以通过该类继承来的getMessage方法获取栈的深度。 3.定义一个IntStack类,它主要实现int基本数据类型的栈功能: (1)无参构造函数,默认栈的深度为16。 (2)有参构造函数,栈的深度通过参数指定。当参数为负数或零时,抛出java.lang包中已有的异常IllegalArgumentException异常。 (3)isEmpty方法和isFull方法,返回值都是boolean.这两个方法用于判断栈是否为空和判断栈是否为满。 (4)pop方法:栈不为空时,实现弹栈功能;栈空时,抛出EmptyStackException异常。 (5)push方法:当栈不满时,实现压栈功能;栈满时,抛出FullStackException异常。 (6) peek函数:栈不为空时,返回栈顶元素值;栈为空时,抛出EmptyStackException异常。
时间: 2024-03-26 15:34:22 浏览: 21
好的,以下是Java代码实现:
1. EmptyStackException类
```java
public class EmptyStackException extends Exception {
public EmptyStackException(String message) {
super(message);
}
}
```
2. FullStackException类
```java
public class FullStackException extends Exception {
private int depth;
public FullStackException(int depth) {
super("The stack is full.");
this.depth = depth;
}
public int getDepth() {
return depth;
}
}
```
3. IntStack类
```java
public class IntStack {
private int[] stack;
private int top;
private int depth;
public IntStack() {
this(16);
}
public IntStack(int depth) {
if (depth <= 0) {
throw new IllegalArgumentException("The depth must be a positive integer.");
}
this.stack = new int[depth];
this.top = -1;
this.depth = depth;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == depth - 1;
}
public int pop() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("The stack is empty.");
}
return stack[top--];
}
public void push(int value) throws FullStackException {
if (isFull()) {
throw new FullStackException(depth);
}
stack[++top] = value;
}
public int peek() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("The stack is empty.");
}
return stack[top];
}
}
```
以上代码实现了一个基本的int类型栈,包括了栈的初始化、判断栈是否为空或满、压栈、弹栈、获取栈顶元素等功能,并且在出现栈空或栈满的情况时,抛出了相应的异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)