简体   繁体   中英

why am I getting nullPointerException

I have the following code; however, it seems that I'm accessing an index in the arraylist that doesn't exist... here's the code. Any help appreciated.

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;

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

No customer assigned here for second BankAccount .

But, you are trying to print customer details. For second BankAccount c would be null . Any operation on null reference results in NullPointerException .

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

Make sure c is not null before making any calls on c to avoid NullPointerException .

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

You need to initialisze your Customer obj in BankAccount class as below.

Customer myCustomer = new Customer();

Also its not recommended to access class variables like you're doing. Create get and set methods and access your Customer obj by invoking getCustomer()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM