It first takes the name of the customer and after it takes the purchase amount of that customer up to ten customer. Then it prints out the name of the customer who purchases most. I have the following code:
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;
And this one is the Class:
public class Store {
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];
}
}
However, I get "java.lang.NullPointerException: null" error. Can you please help me? Thank you.
public Store() { double[] sales=new double[10]; String[] customerNames=new String[10]; }
This declares an entirely new variable named sales
, assigns a new double array to it, and then tosses the local variable it into the bin immediately, as is the fate of all local variables once its scope ends (local vars are scoped to the nearest set of braces, so, after these 2 lines, a closing brace appears: That is where all local vars declared inside, such as your sales
and customerNames
in this code, poof out of existence). The arrays will be garbage collected eventually; nobody has any reference to them anymore.
This does absolutely nothing whatsoever to your field named sales
.
What you presumably want is:
public Store()
{
sales=new double[10];
customer=new String[10];
}