import java.util.ArrayList; import java.util.Scanner;
public class ProbSixThirty {
public static void main(String[] args) { /*customer's name is stored in a corresponding ArrayList*/ ArrayList Customers=new ArrayList<>(); /*the customer's purchase amount is stored in an ArrayList*/ ArrayList Sales=new ArrayList<>(); /*to read input*/ Scanner keyboard=new Scanner(System.in); /*Just to start the while loop*/ double price=999; String name; int n=1; /* Reading customer details , till cashier entering price as 0 */ /* since price 0 is used as sentinel */ while(price>0) { System.out.println("Enter details for customer "+n); System.out.println("Name: "); name=keyboard.nextLine(); /*Add to Customers list */ Customers.add(name); System.out.println("Purchase Amount: "); price=keyboard.nextDouble(); keyboard.nextLine(); /*if price is 0, stop the loop*/ if(price==0) break; //else /*Add to Customers list */ Sales.add(price); n++; } /*Display the name of the best customer*/ System.out.println(" Result: "); /*call the function to find best customer*/ String bestCustomer=nameOfBestCustomer(Customers,Sales); System.out.println("Best Customer is: "+bestCustomer); } /*---------------------------------------------------------------------------*/ /*This function will find and return the customer with lasrgest sale */ private static String nameOfBestCustomer(ArrayList Customers, ArrayList Sales) { /*Assume starting value as largest sale*/ double largest=Sales.get(0); /*store its position*/ int pos=0; /*Search the Sales arraylist find the largest sale, by comparision and replacement. Store the position correspondingly */ for(int i=1;ilargest) { largest=Sales.get(i); pos=i; } } /* obtain the name using pos in Customer list and return */ return Customers.get(pos); } }
Big Java Edition P6.31
Improve the program of Exercise P6.30(WHICH IS ABOVE and works), 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. Implement a method public static ArrayList nameOfBestCustomer(ArrayList sales, ArrayList customers, int topN). If there were fewer than topN customers, include them all.