我正在尝试制作一个程序来计算一系列BankAccount余额的平均值,同时过滤那些低于1000的那些。我们应该使用一个Measurable和Filter接口,所以我创建了一个方法来过滤BankAccounts数组并返回一个已过滤的数组,并使用该数组来计算平均值,这就是我所拥有的:
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;
}
接口及其实现:
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();
}
和测试它的类:
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类
public class BankAccount{
private double balance;
public BankAccount(double initialBalance){
balance = initialBalance;
}
public double getBalance(){
return balance;
}
}
NPE发生在BankMeasure.measure(BankMeasure.java:4) 和Tester.main(Tester.java:13) 我已经读过NullPointerException意味着我正在尝试访问或修改null对象,但我不明白为什么会出现这种情况,任何帮助都非常感谢!