【问题标题】:Trying to print out the "best customer" who has the largest amount spent试图打印出花费最多的“最佳客户”
【发布时间】:2014-11-06 22:34:07
【问题描述】:

这是我到目前为止所得到的。我可以打印出最高金额,但我不知道如何将客户姓名与他们的销售额联系起来,然后将他们的姓名与他们的总数联系起来。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class HW5 {
public static void nameOfBestCustomer(ArrayList<Double> sales,
    ArrayList<String> customers) {
}

public static void main(String[] args) {
    ArrayList<Double> sales = new ArrayList<Double>();
    ArrayList<String> customer = new ArrayList<String>();
    int[][] BestCustomer = new int[1][10];

    Scanner in = new Scanner(System.in);
    System.out.print("Total Number of Customers: ");
    int num = in.nextInt();

    for (int i = 0; i < num; i++) {
        System.out.print("Enter name of customer " + (i + 1) + ": \n");
        customer.add(in.next());

        System.out.print("Total amount for customer " + (i + 1) + ": \n");
        sales.add(in.nextDouble());
    }

    double maximum = Collections.max(sales);
    System.out.println("The Best Customer is " + customer
            + "with a purchase of ");
    System.out.println(String.format("$%.2f", maximum));
}
}

【问题讨论】:

  • 覆盖自定义对象了吗?我假设 HW5 是作业 5?
  • 由于你是使用并行列表,所以使用你的最高金额来获取客户列表的对应索引。
  • 使用循环检查销售额中的值。如果您找到了最大销售量,则保存该索引i。然后打印出该索引处的客户和该索引处的销售额。 sales.get(i)customer.get(i) 之类的。

标签: java arrays arraylist max


【解决方案1】:

您正在使用“并行”列表,即两个单独的列表预计彼此 1:1 对应:

ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> customer = new ArrayList<String>();

随着您的学习,就管理信息而言,这会带来一些困难。如果您想继续使用这些列表,最好的方法是通过列表中的 index 共同识别客户 + 销售。 Collections.max() 只会返回最大值 value,而不是索引,因此您可以手动实现该逻辑。假设您的列表不为空,那么通常的算法是(实现由您自己解决):

  1. 最初假设最高项目是列表中的第一项,因此最高项目的索引最初为 0。
  2. 对于剩余的每个项目,如果该项目大于最高项目,则将新的最高项目索引设置为该项目的索引。

现在您可以使用最高项的索引作为两个数组的索引。

但是,更好的方法是创建一个小的自定义类,将所有关于销售的信息保存在一个地方。例如:

static class Transaction {
    double sale;
    String customer;
}

现在你可以维护一个数组了:

ArrayList<Transaction> transactions = new ArrayList<Transaction>();

在该数组中存储交易:

Transaction t = new Transaction();
t.sale = ...;
t.customer = ...;
transactions.add(t);

那你得有办法比较两个Transactions;您的选择是:

  1. Transaction 实现Comparable&lt;Transaction&gt;,或者
  2. 定义一个可以比较销售额的Comparator&lt;Transaction&gt;

我将把这些细节留给你练习——查看object ordering 上的官方教程,它简短、简洁,包含很好的示例。完成此操作后,您现在拥有使用 Collections.max() 的基础架构(选项 2 的 version that takes a Comparator 或选项 1 的 version that doesn't),max() 现在将直接返回 Transaction 对象,其中包含金额和客户名称。

【讨论】:

  • 非常感谢!我想我开始明白该怎么做了,但以防万一你能检查我的新代码的一部分吗? for (int i = 0; i ; ArrayList 最大值 = (事务); System.out.println("最佳客户是" + " 购买"); System.out.println(String.format("$%.2f", 最大值));
猜你喜欢
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 2010-09-27
  • 1970-01-01
  • 2019-03-14
  • 2013-03-15
相关资源
最近更新 更多