2012-10-04 33 views
0

我有一個foreach循環遍歷每個首選客戶,並總結他們的餘額以創建其總資產。但是,每次查看客戶對象時,都會將其評估爲空。 PreferredCustomer是抽象類Customer的一個子類。我假設我沒有正確地做foreach循環,但我不知道我做錯了什麼。由於某種原因,我的客戶對象爲空。

public static void getBalance() { 
    for(Customer customer: preferredCustomers){ 
     ArrayList<Account> al = customer.getAccountList(); 
     for(Account account: al){ 
      totalAssets+=account.getBalance(); 
      //balance = account.getbalance(); 
     } 
     customer.setBalance(totalAssets); 
    } 
} 

另外,Arraylist AccountList是每個客戶的賬戶對象列表。

+2

您的循環是正確的,它最有可能是preferredCustomers包含空值。 – rodion

+0

你將不得不在你創建/填充'ArrayList'的地方顯示代碼片段。 – Baz

+2

您的getBalance函數沒有收到餘額。 – Wug

回答

1

在未來,如果你的代碼拋出一個NPE,你應該在你的帖子異常的指針哪一行對應於你的示例代碼:

  • 如果您在for(Customer拋出NPE循環,那麼你的preferredCustomers字段是null
  • 如果它在customer.getAccountList()行上拋出NPE,那麼preferredCustomers集合中的元素之一是null
  • 如果它在for(Account account循環中拋出一個NPE,那麼其中一個preferredCustomers的帳戶列表爲null
  • 如果它在totalAssets+=account.getBalance();行上拋出一個NPE,則列表中的一個帳戶是null。它也可能是平衡字段是一個nullLong對象。

由於@ColinD提到,推薦學習how to use a debugger in Eclipse

相關問題