在我编写的这个程序中,我必须打印出在商店中花费最多的客户的名字。我需要帮助在数组列表中搜索花费最多的客户。
package bestcustomer;
import java.util.*;
/**
*
* @author muf15
*/
public class BestCustomer {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
sales.add(salesAmount);
System.out.println("Enter customers name");
names.add(in.next());
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer(sales, names);
}
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales;
return name;
}
}
答案 0 :(得分:1)
您应该将这两个字段包含在名为Customer
的类中,然后再包含
使用Collections.max();
Collections.max(yourCollection, customComparator);
答案 1 :(得分:1)
您应该考虑让Customer成为一个类,但是这会找到您当前数据结构的名称:
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales = 0;
int index = -1;
for(int i = 0; i < sales.size(); i++) {
if(sales.get(i) > maxSales) {
index = i;
maxSales = sales.get(i);
}
}
if(index == -1) {
return null; //lists are empty
}
return customers.get(index);
}
答案 2 :(得分:0)
我可能有点晚了..
我认为,如果您创建一个包含两个字段name
和sale
的Customer类,那么其他答案就会提到更好的设计。
然后在BestCustomer
中,您可以遍历客户列表,找到最高销售额并返回名称。
对BestCustomer
private ArrayList<Customer> customers = new ArrayList<Customer>();
public BestCustomer(){
Scanner in = new Scanner(System.in);
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
System.out.println("Enter customers name");
String name = in.next();
customers.add(new Customer(name, salesAmount));
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer();
System.out.print(bestCustomer);
}
private double highestSale(){
double highestSale = 0;
for(Customer c: customers)
if (c.getSales() > highestSale)
highestSale = c.getSales();
return highestSale;
}
public String nameOfBestCustomer(){
for (Customer c: customers)
if(c.matchSale(highestSale()))
return c.getName();
return null;
}
}
这是Customer
public class Customer {
private String name;
private double sales;
public Customer(String name, double salesAmount) {
this.name = name;
sales = salesAmount;
}
public boolean matchSale(double sales){
return this.sales == sales;
}
public double getSales(){
return sales;
}
public String getName(){
return name;
}
}
我是初学者,所以我很确定有更有效的方法。我也使用两个getters
,据我所知,这不是更好的设计..
答案 3 :(得分:0)
在Java8中,如果像Customer
这样定义mikey
,则
customers.stream()
.max(Comparator.comparing(Customer::getSales))
.get()
.getName()