【发布时间】:2015-03-01 18:06:40
【问题描述】:
我之前写了一个完整的成功程序,由7个类(Date,Address,Time,Customer,Course,InClassCourse,OnLineCourse),一个接口(@987654328@)组成) 当然还有测试类 (CustomerTest)。接口Invoice 有一个方法createInvoice,它在Customer 类中实现。在测试用例中,我创建了 3 个新客户,添加了他们各自的课程,然后根据他们注册的课程数量、他们注册的课程类型以及课程是否为 InClassCourse 或OnLineCourse,最后打印出信息对话框。客户和课程列表保存在两个单独的数组列表中:
ArrayList<Customer> customerList = new ArrayList<Customer>();
ArrayList<Course> courseList = new ArrayList<Course>();
使用增强的 for 循环,我以多态方式遍历 customerList 并为每个客户创建发票。
我现在编写了一个附加类CreateFiles,其中包含一个新的客户和课程列表,它将客户数据写入文件 customers.txt 并将课程数据写入文件 courses.txt强>。 CreateFiles 有一个方法 writeCustomers 和 writeCourses。
我不熟悉异常并且仍在学习。要修改我的程序,我想添加一个名为 CustomerNotEnrolledException 的用户指定异常。 Customer 类中的createInvoice 方法如果客户在他的列表中没有任何课程(我的几个客户没有注册任何课程)将抛出CustomerNotEnrolledException,然后在我的测试类中处理这个异常。
我的问题是如何在 try 块中编写语句来检查客户是否注册了任何课程,如果没有取消它们。我需要这样做,因为在我已经淘汰了未注册的客户,我将在Test case中添加方法readCustomers、readCourses和generateInvoice,并使用它们来读取customers.txt文件和courses .txt 文件来创建客户并将他们添加到customerList,以及创建课程,这些课程将添加到他们各自的客户中。
我已经创建了一个名为 CustomerNotEnrolledException 的异常类,它扩展了异常:
public class CustomerNotEnrolledException extends Exception
{
public CustomerNotEnrolledException()
{
super("Customer not enrolled");
}
我原来的 createInvoice 方法是这样的:
public String createInvoice()
{
double total;
if (cType==CustomerType.STUDENT)
total = 25;
else if (cType==CustomerType.FACULTY)
total = 50;
else if (cType==CustomerType.GOVERNMENT)
total = 35;
else
total = 0;
for(Course course:this.courseList)
{
total += course.calculateCharge(this.cType);
}
return (String.format("%s\t\t%d\t\t$%.2f", this.name,
this.accountNumber,total));
}
【问题讨论】:
-
不要描述我们的代码,而是发布它的相关部分,并发布您想要编写的方法及其 javadoc 描述它应该做什么。
标签: java exception arraylist exception-handling throws