-3

how do if fix the Exception in thread "main" java.lang.NullPointerException at BankSystem.Branches.findCustomer(Branches.java:44) I'm new to coding and java is my first language and I keep getting this error I don't know to fix it.

package BankSystem;

import java.util.ArrayList;

public class Branches {

private String name;
private ArrayList<Customers> newCustomer;

public Branches(){
}

public Branches(String name) {
    this.name = name;
    this.newCustomer = new ArrayList<>();
}

public ArrayList<Customers> getNewCustomer(){
    return newCustomer;
}

public String getName() {
    return name;
}

public boolean addCustomer(String name, double amount) {
    if (findCustomer(name) == null) {
        this.newCustomer.add(new Customers(name, amount));
        return true;
    }
    return false;
}

public boolean addTranstraction(String name, Double amount) {
    Customers existingCustomer = findCustomer(name);
    if (existingCustomer != null) {
        existingCustomer.addTransactions(amount);
        return true;
    }
    return false;
}

private Customers findCustomer(String name) {
    for(int i=0; i<this.newCustomer.size(); i++){
        Customers checkedCustomer = this.newCustomer.get(i);
        if(checkedCustomer.getName().equals(name)) {
            return checkedCustomer;
        }
    }
    return null;
}

}

  • 1
    In your constructor you need to do: `this.newCustomer = new ArrayList();` – Mikaal Anwar May 19 '18 at 19:30
  • I tried that it does not work. – Ahmed Abdullah May 19 '18 at 19:34
  • 1
    The default constructor is probably being called. If so, `newCustomer` will never be created. – 001 May 19 '18 at 19:35
  • Welcome to StackOverflow! To make it easier for people to help you, please fix the indents, include the code that creates and uses the instance of branch, and let people know which line of your code has the NullPointerException (since we don't see line numbers). Good luck! – Ellen Spertus May 19 '18 at 19:41

2 Answers2

1

I think that the default constructor for your class is being called, which doesn't initialize newCustomer. You would need to look at the code that initializes the Branch that is giving you the error. The NullPointerException just means that you are trying to use an object that has not been initialized.

OrdoFlammae
  • 721
  • 4
  • 13
0

The problem in your findCustomer might be that if the customer you are looking for in addTranstraction does not exist, which would cause it to return null, and trying to access a null variable is what causes your nullPointerException.