可以找出我收到java.lang.NullPointerException的原因

时间:2015-01-31 20:32:33

标签: java nullpointerexception

我看了几个其他的踏板,但我仍然无法找到我出错的地方。我试图创建一个Account对象数组并从文本文件中扫描以填充它。感谢您提供任何帮助或指点。

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

2 个答案:

答案 0 :(得分:1)

查看如何初始化您的帐户对象,您的所有客户端都为空:

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

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

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

你会得到NPE。

解决方案:不要使用null客户端。在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]);
}

答案 1 :(得分:1)

您的自我设置客户端为 null ,然后调用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
    }
}