简体   繁体   中英

Can't figure out why I'm getting a java.lang.NullPointerExceptio

I looked at a couple other treads and I still couldn't find out where I'm going wrong. I'm trying to make an array of Account objects and scan from a text file to fill it out. Thanks for any help or direction pointing.

import java.util.*;
import java.io.*;


public class Bank {

    private static Account[] accounts = new Account[10];
    private static int numAccounts = 0;

    public static void main(String[] args) throws Exception  { 
        Scanner fileScan = new Scanner(new File("bankdata.txt"));

        for(int i=0; i<accounts.length;i++){
            accounts[i] = new Account(null, i, i); //(client, balance, accountNum)
        }

        while(fileScan.hasNext()){
            accounts[numAccounts].getClient().setFName(fileScan.next());
            accounts[numAccounts].getClient().setLName(fileScan.next());
            accounts[numAccounts].getClient().setAge(fileScan.nextInt());
            accounts[numAccounts].getClient().setPhoneNum(fileScan.nextInt());
            accounts[numAccounts].setBalance(fileScan.nextDouble());
            accounts[numAccounts].setAccountNum(fileScan.nextInt());

            numAccounts++;
            System.out.println(accounts[numAccounts]);
        }
        fileScan.close();
    }
}

Looking at how you initialize your Account objects, all your Clients are null:

accounts[i] = new Account(null, i, i); //(client, balance, accountNum)

Then when you try to use a Client variables,

accounts[numAccounts].getClient().setFName(fileScan.next());

you'll get the NPE thrown.

Solution: don't use null clients. Create your Client in the while loop:

while(fileScan.hasNext()){
    String fName = fileScan.next();
    String lName = fileScan.next();
    int age = fileScan.nextInt();
    String phoneNumber = fileScan.next();

    Client client = new Client(....); //use info above

    accounts[numAccounts].setClient(client);
    accounts[numAccounts].setBalance(fileScan.nextDouble());
    accounts[numAccounts].setAccountNum(fileScan.nextInt());

    numAccounts++;
    System.out.println(accounts[numAccounts]);
}

You your self setting client as null , and then calling function on null reference that is why you are getting NPE

accounts[i] = new Account(null, i, i); //(client, balance, accountNum)

Calling a method on a null reference or trying to access a field of a null reference will trigger a NPE.

Example :

public class Test
{
    public static void main(String[] args)
    {
        Object obj = null;
        obj.toString(); //cause Null Pointer Exception
    }
}

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