So, I would say I'm pretty novice at programming and most of my background comes from C++, where I'm dealing with pointers and references and whatnot. I've started to learn Java, and I had to write this example program but for some reason I cannot escape the NullPointerException in the program. I tried searching for answers, and I understand the other answers I've seen but I can't see why I would have a null pointer. Thinking maybe I was coding it entirely wrong, I rewrote the program in C++, but it seems to work with no problems which just boggled my mind even more. I'm thinking it's possibly because of the way Java handles references, since there's no concepts of pointers and addresses.
If it would help at all, I could post the header/class and a stack dump as well.
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();
}
}
}
}
The same program rewritten in C++ (compiles fine and runs no problem)
#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;
}