1

I have the following test class

public class Driver
{
    public static void main(String [] args)
        {
             BankAccount[] b1 = {new BankAccount(200), new BankAccount(300), new BankAccount(250), new BankAccount(300), new BankAccount(200)};
              BankAccountGroup bag = new BankAccountGroup(b1);                      

        }

And BankAccountGroup:

public class BankAccountGroup 
{ 
private BankAccount bank[];
public BankAccountGroup(BankAccount[]b)
{
for(int i =0; i<5;i++)
{
bank[i] = b[i];
}
}

these are just snippets of the whole code. Im getting a nullpointerexception for these two lines: - bank[i] = b[i]; - BankAccountGroup bag = new BankAccountGroup(b1); Please help

3 Answers 3

1

When you declare bank[] in the BankAccountGroup class it looks like you forgot to give it a length. Because of this, when you call bank[i] in your for loop, anything after i=0 is probably going to give you an error.

something like

private BankAccount[] bank = new BankAccount[5];
Sign up to request clarification or add additional context in comments.

1 Comment

Can you mark this as the answer? IMTRYINGTOGETSOMEPOINTS.
1

Either initialize your array first(Bad).

Or assign it from the value you pass the constructor.

private BankAccount[] bank;
public BankAccountGroup(BankAccount []){
       bank = b;
}

Comments

0

You are not initializing the bank array. You also shouldn't assume that the argument will have a length of 5 elements. I would rewrite the class to something like this:

 public class BankAccountGroup 
{ 
    private BankAccount bank[];

    public BankAccountGroup(BankAccount[]b)
    {
        if (b != null)
        {
            bank = new BankAccount[b.length];

            for(int i=0; i<b.length;i++)
            {
                bank[i] = b[i];
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.