问题 问答题

[说明]
类Queue表示队列,类中的方法如表4-12所示。
表4-12 类Queue中方法说明表

方法 说明
IsEmpty() 判断队列是否为空,如果队列不为空,返回true;否则,返回false
Enqueue(object NewNode) 入队操作
Dequeue() 出队操作。如果队列为空,则抛出异常
类Node表示队列中的元素;类EmptyQueueException给出了队列中的异常处理操作。
[Java代码]
public class testmain //主类
public static viod main (string args[])
Queue q= new Queue;
q.enqueue("first!");
q.enqueue("second!");
q.enqueue("third!");
(1)
while(true)
system.out.println(q.dequeue());

catch( (2) )

public class Queue //队列
node m_firstnode;
public Queue()m_firstnode=null;
public boolean isempty()
if (m_firstnode= =null)
return true;
else
return false;

public viod enqueue(object newnode)//入队操作
node next = m_firstnode;
if (next = = null) m_firstnode=new node(newnode);
else
while(next.getnext() !=null)
next=next.getnext();
next.setnext(new node(newnode));


public object dequeue() (3) //出队操作
object node;
if (is empty())
(4)
else
node =m_firstnode.getobject();
m_firstnode=m_firstnode.getnext();
return node;



public class node //队列中的元素
object m_data;
node m_next;
public node(object data) m_data=data; m_next=null;
public node(object data,node next) m_data=data; m_next=next;
public void setobject(object data) m_data=data;
public object getobject(object data) return m_data;
public void setnext(node next)m_next=next;
public node getnext() return m_next;

public class emptyqueueexception extends (5) //异常处理类
public emptyqueueexception()
system. out. println ( "队列已空!" );

答案

参考答案:这是一道要求读者掌握Java异常处理机制的程序分析题。本题的解答思路如下。
异常是指计算机程序执行期间中断的正常流程的事件。例外是在程序运行过程中发生的异常事件,比如除0溢出、数组越界、文件找不到等,这些事件的发生将阻止程序的正常运行。
当一个方法中发生错误时,该方法创建一个对象(该对象称之为异常对象)并将它交给运行时系统。异常对象包含了关于错误的信息,即包括错误的类型和错误发生时程序的状态。
“抛出一个异常”是指创建异常对象并将它交给运行时系统。Java的异常处理是通过try、catch、throw、 throws和finally 5个关键字来实现的。这几个关键字的解释如表4-15所示。
表4-15 Java异常处理关键字说明表

语句