所以,我会说我是编程的新手,我的大部分背景来自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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
用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;
}
Run Code Online (Sandbox Code Playgroud)
BankAccount[] accountsList = new BankAccount[5];
Run Code Online (Sandbox Code Playgroud)
这不会创建填充数组的对象.
您必须遍历数组并创建对象以填充它.
for(int i = 0; i< accountList.length; i++) {
accoutnList[i] = new BankAccount();
}
Run Code Online (Sandbox Code Playgroud)
在其他编程语言中,数组的构造也意味着这个数组被填充,在java中你创建了一个数组,但这并不意味着数组是用适当的对象初始化的.实际上它持有空引用,因此观察到NPE.
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |