
练习文件:
queuefullexception.java
queueemptyexception.java
固定队列.java
qexcdemo.java
在这个项目中,为队列类(queue)创建了两个自定义异常,分别指示满队列和空队列的错误情况。这些异常由 put() 和 get() 方法使用。
队列异常:
fixedqueue 类实现:
异常和fixedqueue类代码:
queuefullexception.java
public class queuefullexception extends exception {
int size;
queuefullexception(int s) { size = s; }
public string tostring() {
return "\nqueue is full. maximum size is " + size;
}
}
queueemptyexception.java:
public class queueemptyexception extends exception {
public string tostring() {
return "\nqueue is empty.";
}
}
fixedqueue.java:
class fixedqueue implements icharq {
private char q[];
private int putloc, getloc;
public fixedqueue(int size) {
q = new char[size];
putloc = getloc = 0;
}
public void put(char ch) throws queuefullexception {
if (putloc == q.length)
throw new queuefullexception(q.length);
q[putloc++] = ch;
}
public char get() throws queueemptyexception {
if (getloc == putloc)
throw new queueemptyexception();
return q[getloc++];
}
}
使用 qexcdemo 进行测试:
qexcdemo类模拟队列的使用:
插入元素直到超过限制,抛出 queuefullexception。
它尝试通过抛出 queueemptyexception 从空队列中删除元素。
class qexcdemo {
public static void main(string args[]) {
fixedqueue q = new fixedqueue(10);
char ch;
int i;
try {
for(i=0; i < 11; i++) {
system.out.print("attempting to store : " + (char) ('a' + i));
q.put((char) ('a' + i));
system.out.println(" - ok");
}
} catch (queuefullexception exc) {
system.out.println(exc);
}
try {
for(i=0; i < 11; i++) {
system.out.print("getting next char: ");
ch = q.get();
system.out.println(ch);
}
} catch (queueemptyexception exc) {
system.out.println(exc);
}
}
}
更新了 icharq 界面:
icharq 现在在 put() 和 get() 方法中包含抛出异常,反映了固定队列抛出的异常。
public interface ICharQ {
void put(char ch) throws QueueFullException;
char get() throws QueueEmptyException;
}
预期输出:
程序会显示指示元素插入和删除成功的消息,以及错误消息:
队列已满。当队列已满时,最大大小为 10。
队列为空。当尝试从空队列中删除元素时。
以上就是尝试向 Queue 类添加异常的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号