0

我有以下代码;但是,似乎我正在访问数组列表中不存在的索引......这是代码。任何帮助表示赞赏。

import java.util.*;

public class Main {


    public static void main(String[] args) {

        ArrayList<BankAccount> allAccounts = new ArrayList<BankAccount>();

        Customer john = new Customer();
        john.firstName = "John";
        john.lastName = "Doe";

        BankAccount johnBa = new BankAccount();
        johnBa.accNumber = "111-222-333";
        johnBa.balance = 200;
        johnBa.myCustomer = john;

        Customer nick = new Customer();
        nick.firstName = "Nick";
        nick.lastName = "James";

        BankAccount nickBa = new BankAccount();
        nickBa.accNumber = "222-333-444";
        nickBa.balance = 100;

        allAccounts.add(johnBa);
        allAccounts.add(nickBa);

        ArrayList<Customer> allCust = new ArrayList<Customer>();
        allCust = extractCustomers(allAccounts);

        for(Customer c : allCust) {
            System.out.println(c.firstName+" "+c.lastName);
        }       


    }

    static ArrayList<Customer> extractCustomers(ArrayList<BankAccount> ba) {
        ArrayList<Customer> cu = new ArrayList<Customer>();

        for(BankAccount b: ba) {
            cu.add(b.myCustomer);
        }

        return cu;
    }

}


public class BankAccount {

    String accNumber;
    double balance; 

    Customer myCustomer;

}

public class Customer {

    String firstName;
    String lastName;

}
4

2 回答 2

4
 BankAccount nickBa = new BankAccount();
        nickBa.accNumber = "222-333-444";
        nickBa.balance = 100;

没有客户第二次分配到这里BankAccount

但是,您正在尝试打印客户详细信息。对于第二个BankAccountc 将是null. 对引用的任何操作都会null导致NullPointerException.

 for(Customer c : allCust) {
            System.out.println(c.firstName+" "+c.lastName);
        }   

null在对 c 进行任何调用以避免之前确保 c 不是NullPointerException

  for(Customer c : allCust) {
           if(c != null){
            System.out.println(c.firstName+" "+c.lastName);
               }
        } 
于 2012-10-25T20:21:19.093 回答
0

您需要在 BankAccount 类中初始化您的 Customer obj,如下所示。

Customer myCustomer = new Customer();

也不建议像您正在做的那样访问类变量。创建 get 和 set 方法并通过调用 getCustomer() 访问您的 Customer obj

于 2012-10-25T20:25:52.623 回答