不明白为什么我会收到 java.lang.NullPointerExceptio

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

我查看了其他几个踏板,但仍然找不到哪里出错了。我正在尝试制作一个帐户对象数组并从文本文件中扫描以填写它。感谢您的帮助或指点。

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();
    }
}

查看您如何初始化 Account 对象,您的所有 Clients 均为空:

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

然后当你尝试使用客户端变量时,

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

你会被抛出 NPE。

解决方案:不要使用空客户端。在 while 循环中创建您的客户端:

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]);
}

您将自己的客户端设置为 null ,然后在空引用上调用函数,这就是您获得 NPE

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

在空引用上调用方法或尝试访问空引用的字段将触发 NPE。

示例:

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