0

所以我有这两种方法:第一种是遍历客户的数组列表并返回一个值,该值c是类型 IDStringArrayList.

private Customer findCustomer(String id){
    Customer c;
    for(Customer customer : customers){
        if(customer.getID().equals(id)){
            c = customer;
            return c;
        }
    }
    return null;
}

然后我有第二个,当有人在我的临时电影租赁程序的 GUI 中访问此方法并传入电影时,他们租用的日期和客户的 id

public void movieRented(Movie m, Date rented, String id){
    m.setDateRented(rented);
    Customer c = findCustomer(id);
    c.addMovie(m);
    m.setIntStock(false);
}

我收到有关这两种方法的错误消息,我只是想确保它们至少看起来正确。

4

2 回答 2

3

注意你返回的是 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);
 }
  .
  .
  .
}
于 2013-07-09T19:08:12.027 回答
0

我不确定这是否正确,但这一行可能存在拼写错误:

m.setIntStock(false);

看起来应该是

m.setInStock(false);

如果找不到客户,您返回 null 似乎也可能会遇到麻烦。如果您不确定为什么会发生这种情况,我建议您使用一些简单的 println 语句。例如:

System.out.println("customer id = " + customer.getId() + " id= " + id);
于 2013-07-09T19:03:14.320 回答