“如何修复”;java.lang.NullPointerException:null";?
它首先获取客户的名称,然后获取该客户的购买金额,最多为10个客户。然后打印出购买最多的客户的姓名。我有以下代码:“如何修复”;java.lang.NullPointerException:null";?,java,nullpointerexception,Java,Nullpointerexception,它首先获取客户的名称,然后获取该客户的购买金额,最多为10个客户。然后打印出购买最多的客户的姓名。我有以下代码: Store cashier=new Store(); double[] purchase=new double[10]; String[] customer=new String[10]; for(int i=0;i<10;i++){
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;
Store cashier=new Store();
double[]购买=新的double[10];
字符串[]客户=新字符串[10];
对于(int i=0;i
这声明了一个名为sales
的全新变量,为其分配了一个新的双数组,然后将局部变量立即扔进垃圾箱,其作用域结束后,所有局部变量的命运也是如此(本地变量的作用域是最近的一组大括号,因此,在这两行之后,将出现一个右大括号:在这里,所有在内部声明的本地变量,例如您的销售
和客户名称
,都不存在)。数组最终将被垃圾收集;没有人再引用它们了
这对名为sales
的字段绝对没有任何影响
你大概想要的是:
public Store()
{
sales=new double[10];
customer=new String[10];
}
你知道NPE是什么以及如何处理它吗?哪一行抛出异常?@Thomas If I'm not right“sales[counter]=saleAmount;”这一行抛出异常。首先我输入名称,例如“Jack”,然后输入金额,例如“10”紧接着它就出现了错误。stacktrace是否提到了这一行?提示:每次调用addSale()时
计数器设置为0
。这会产生什么后果?旁注:您应该学习如何使用调试器调试程序。这是一项最好在早期学习的技能。还有另一个设计问题:索引
仅用于贝斯特客户名称()
所以它应该是一个局部变量,而不是一个实例字段。另外,为什么在第一个代码片段中有这些数组?你将每个销售添加到存储
实例中,这样它们就可以只是循环中的局部变量。你说得太对了。我怎么会错过这样一个明显的错误呢?@Thomas当我回来看到这个。
public Store()
{
double[] sales=new double[10];
String[] customerNames=new String[10];
}
public Store()
{
sales=new double[10];
customer=new String[10];
}