注意你返回的是 null,所以你可以有一个NullPointerException
private Customer findCustomer(String id){
Customer c;
for(Customer customer : customers){
if(customer.getID().equals(id)){
c = customer;
return c;
}
}
return null;
}
你可以考虑改进你的方法
private Customer findCustomer(String id){
Customer c=null;
for(Customer customer : customers){
if(customer.getID().equals(id)){
c = customer;
break;
}
}
return c;
}
或者现在更好,使用自定义异常
private Customer findCustomer(String id) throws NoFoundCustomerException{
Customer c=null;
for(Customer customer : customers){
if(customer.getID().equals(id)){
c = customer;
break;
}
}
if(c == null){
throw new NoFoundCustomerException();
}
return c;
}
在客户端代码中,您可以执行以下操作:
public void movieRented(Movie m, Date rented, String id){
try{
m.setDateRented(rented);
Customer c = findCustomer(id);
c.addMovie(m);
m.setIntStock(false);
}catch(NotFoundedCustomerException e){
JOptionPane.showMessage(null,"Customer doesn't exist");
}
}
你的例外看起来像这样
public class NotFoundedCustomerException extends Exception{
public NotFoundedCustomerException(){
super();
}
public NotFoundedCustomerException(String message){
super(message);
}
.
.
.
}