它首先获取客户的姓名,然后获取该客户的购买金额,最多可达十个客户。然后它会打印出购买次数最多的客户的姓名。我有以下代码:
Store cashier=new Store();
double[] purchase=new double[10];
String[] customer=new String[10];
for(int i=0;i<10;i++){
customer[i]=JOptionPane.showInputDialog("Please enter the name of the customer");
String purchaseString=JOptionPane.showInputDialog("Please enter the buying amount of the customer");
purchase[i]=Double.parseDouble(purchaseString);
cashier.addSale(customer[i],purchase[i]);
}
JOptionPane.showMessageDialog(null,"The best customer is"+cashier.nameOfBestCustomer());
break;
这是班级:
公开课店 {
private double[] sales;
private String[] customerNames;
private int counter;
private double maxsale;
private int index;
public Store()
{
double[] sales=new double[10];
String[] customerNames=new String[10];
}
public void addSale(String customerName, double saleAmount)
{
counter=0;
sales[counter]=saleAmount;
customerNames[counter]=customerName;
counter=counter+1;
}
public String nameOfBestCustomer(){
maxsale=sales[0];
for(int i=0;i<10;i++){
if(sales[i]>maxsale){
maxsale=sales[i];
index=i;
}
}
return customerNames[index];
}
}
但是,我收到“java.lang.NullPointerException:null”错误。你能帮我么?谢谢你。
public Store() { double[] sales=new double[10]; String[] customerNames=new String[10]; }
这声明了一个名为sales
的全新变量,为其分配一个新的双精度数组,然后立即将局部变量扔进垃圾箱,就像一旦其作用域结束后所有局部变量的命运一样(局部变量的作用域是最近的一组大括号,因此,在这两行之后,会出现一个右大括号:这是在内部声明的所有本地变量的位置,例如这段代码中的
sales
和 customerNames
,噗地不存在了) 。数组最终会被垃圾回收;没有人再参考他们了。
这对您名为
sales
的领域绝对没有任何作用。
您可能想要的是:
public Store()
{
sales=new double[10];
customer=new String[10];
}