0

I am trying to make a program that computes the average of a series of BankAccount balances while filtering the ones that are below 1000. We were supposed to use a Measurable and Filter interface so I created a method to filter an array of BankAccounts and return a filtered array, and use that one to compute the average, here is what i have:

public class Data{
   public static double average(Object[] objects, Measurable meas){
      double sum = 0;
      for(int i = 0; i < objects.length; i++){
        sum = meas.measure(objects[i]) + sum;
      }
      if(objects.length > 0)
        return sum / objects.length;
      else 
        return 0;
   }

   public static Object[] filter(Object[] objects, Filter filter){
     Object[] newarray = new Object[objects.length];
     int cntr = 0;
     for(int i = 0; i < objects.length; i++){
        if(filter.accept(objects[i])){
            newarray[i] = objects[i];
            cntr++;
        }
    }
     Object[] result = new Object[cntr];
     System.arraycopy(newarray, 0, result, 0, cntr);
     return result;
}

interfaces and their implementations:

public interface Measurable{
double measure(Object x);
}
public interface Filter{
boolean accept(Object x);
}

public class BankFilter implements Filter{
public boolean accept(Object x){
    BankAccount account = (BankAccount) x;
    return account.getBalance() > 1000;
}

public class BankMeasure implements Measurable{
public double measure(Object x){
    BankAccount account = (BankAccount) x;
    return account.getBalance();
}

and the class to test it:

public class Tester{
public static void main(String[] args){
    Measurable bankMeas = new BankMeasure();
    Filter filter = new BankFilter();
    BankAccount acc1 = new BankAccount(200);
    BankAccount acc2 = new BankAccount(200);
    BankAccount acc3 = new BankAccount(3000);
    BankAccount acc4 = new BankAccount(50);
    BankAccount acc5 = new BankAccount(4000);
    BankAccount[] ar = {acc1, acc2, acc3, acc4, acc5};
    Object[] filteredAcc = Data.filter(ar,filter);
    for(int i = 0; i < filteredAcc.length; i++){
        System.out.println(bankMeas.measure(filteredAcc[i]));
    }

    System.out.println(Data.average(filteredAcc, bankMeas));
    }
}    

BankAccount class

public class BankAccount{
private double balance;
public BankAccount(double initialBalance){
    balance = initialBalance;
}
public double getBalance(){
    return balance;
}
}

The NPE occurs at BankMeasure.measure(BankMeasure.java:4) and Tester.main(Tester.java:13) I have read that the NullPointerException means I am trying to access or modify a null Object but I don't see why that would be my case, any help much appreciated!

totoro01
  • 1
  • 2

0 Answers0