In the Store class, make an ArrayList of customers, store name, and address implement methods
public void addSale(Customer c) that will add customers to the arraylist.
public void RemoveCustomer(int id);
public void UpdateCustomerRecord(int Id);
public displayAll();
public String nameOfBestCustomer() to record the sale and return the name of the customer with the largest sale.
public ArrayList nameOfBestCustomers(int topN)
 so that it displays the top customers, that is, the topN customers with the largest sales, where topN is a value that the user of the program supplies.
Â
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class Store {
private String name;
private String address;
private ArrayList<Customer> customers;
public Store(String name, String address) {
this.name = name;
this.address = address;
customers = new ArrayList<>();
}
public void addSale(Customer c) {
customers.add(c);
}
public void removeCustomer(int id) {
int index = -1;
for (int i = 0; i < customers.size(); i++) {
if (customers.get(i).getId() == id) {
index = i;
break;
}
}
if (index != -1) {
customers.remove(index);
}
}
public void updateCustomerRecord(int id) {
int index = -1;
for (int i = 0; i < customers.size(); i++) {
if (customers.get(i).getId() == id) {
index = i;
break;
}
}
if (index != -1) {
Scanner in = new Scanner(System.in);
System.out.println("Name:");
customers.get(index).setName(in.nextLine());
System.out.println("Sale:");
customers.get(index).setSale(Double.parseDouble(in.nextLine()));
System.out.println("ID:");
customers.get(index).setId(Integer.parseInt(in.nextLine()));
}
}
public void displayAll() {
for (Customer customer : customers) {
System.out.println(customer);
}
}
public String nameOfBestCustomer() {
int index = 0;
for (int i = 0; i < customers.size(); i++) {
if (customers.get(i).getSale() > customers.get(index).getSale()) {
index = i;
}
}
return customers.get(index).getName();
}
public ArrayList<String> nameOfBestCustomers(int topN) {
customers.sort(Comparator.comparing(Customer::getSale));
ArrayList<String> names = new ArrayList<>();
for (int i = customers.size() - 1; i >= customers.size() - topN; i--) {
names.add(customers.get(i).getName());
}
return names;
}
}
Comments
Leave a comment