所以,我会说我是编程的新手,我的大部分背景来自C ++,我在处理指针和引用等等。我已经开始学习Java了,我不得不编写这个示例程序,但由于某种原因,我无法逃避程序中的NullPointerException。我试着寻找答案,我理解我见过的其他答案,但我不明白为什么我会有一个空指针。想到也许我编码完全错了,我用C ++重新编写了程序,但它似乎没有任何问题,这让我的想法更加困难。我认为这可能是因为Java处理引用的方式,因为没有指针和地址的概念。
如果它有帮助,我也可以发布标题/类和堆栈转储。
package com.company;
import java.util.Random;
public class Main {
public static void main(String[] args)
{
// Create some bank accounts.
BankAccount[] accountsList = new BankAccount[5];
// Create a list of random names.
String[] namesList = {"Bob", "Alice", "John", "Matt", "Billy"};
// Set all account names, and print initial balance.
for (int x = 0; x < 5; x++)
{
accountsList[x].SetCustomerName(namesList[x]);
System.out.println("Initial Balance // Account: " + accountsList[x].GetCustomerName());
System.out.println("Balance: $" + accountsList[x].GetBalance());
System.out.println();
}
// Conduct n rounds of simulated deposit/withdrawal transactions for each account.
for (int rounds = 5; rounds < 0; rounds--)
{
for (BankAccount x : accountsList)
{
System.out.println("Transaction Inquiry // Account: " + x.GetCustomerName());
x.DepositFunds(Math.abs(new Random().nextInt()));
x.WithdrawFunds(Math.abs(new Random().nextInt()));
System.out.println();
}
}
}
}
用C ++重写相同的程序(编译好并且没有问题)
#include "BankAccount.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
int main(int nArgs, char* pszArgs[])
{
// Seed the RNG.
srand(time(NULL));
// Create some bank accounts.
BankAccount accountsList[5];
// Create a list of random names.
std::string namesList[] = { "Bob", "Alice", "John", "Matt", "Billy" };
// Set all account names, and print initial balance.
for (int x = 0; x < 5; x++)
{
accountsList[x].SetCustomerName(namesList[x]);
std::cout << "Initial Balance // Account: " << accountsList[x].GetCustomerName() << "\n";
std::cout << "Balance: $" << accountsList[x].GetBalance() << "\n\n";
}
// Conduct n rounds of simulated deposit/withdrawal transactions for each account.
for (int rounds = 5; rounds > 0; rounds--)
{
for (BankAccount &x : accountsList)
{
std::cout << "Transaction Inquiry // Account: " << x.GetCustomerName() << "\n";
x.DepositFunds(abs(rand()));
x.WithdrawFunds(abs(rand()));
std::cout << std::endl;
}
}
return 0;
}
答案 0 :(得分:5)
BankAccount[] accountsList = new BankAccount[5];
这不会创建填充数组的对象。
您必须遍历数组并创建对象以填充它。
for(int i = 0; i< accountList.length; i++) {
accoutnList[i] = new BankAccount();
}
在其他编程语言中,数组的构造也意味着这个数组被填充,在java中你创建了一个数组,但这并不意味着数组是用适当的对象初始化的。实际上它持有空引用,因此观察到NPE。
答案 1 :(得分:0)
与C ++不同,Java支持零长度数组。但这确实引入了一些建设开销。您需要通过编写
来初始化accountsList
BankAccount[] accountsList = new accountsList[5];
其中accountsList
是数组对象的引用。重要的是,accountsList
中的元素设置为null
。你需要自己初始化每一个。宽松地将accountsList
视为std::shared_ptr<std::array<std::shared_ptr<T>>>
类型。
答案 2 :(得分:0)
您需要先创建BankAccount对象,然后设置其&#34; customerName&#34;属性,否则你在null对象上调用该方法。
accountsList[x] = new BankAccount();
accountsList[x].setCustomerName(namesList[x]);
创建阵列时,您也不会创建自己的元素。