计算平均值、最小值和最大值
您正在分析咖啡店的销售数据。数据包含每笔交易的日期、咖啡名称、支付方式、售出数量和交易金额,如下示例所示。请计算交易金额的平均值、最小值和最大值,并格式化为保留 2 位小数。
| date | coffee_name | payment_method | quantity | amount |
|---|---|---|---|---|
| 3/1/24 | Latte | cash | 1 | $6.26 |
| 3/5/24 | Hot Chocolate | card | 3 | $32.51 |
| 3/6/24 | Americano | card | 2 | $18.70 |
LocalDate、Arrays 和 List 等必要包已为您导入。
本练习是课程的一部分
Java 数据清洗
练习说明
- 使用
stats计算交易金额的平均值。 - 使用
stats计算交易金额的最小值和最大值。
交互式实操练习
通过完成这段示例代码来试试这个练习。
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
public class CoffeeSalesExample {
private record CoffeeSales(LocalDate date, String coffeeName,
String paymentMethod, int quantity, double amount) {
}
public static void main(String[] args) {
List sales = Arrays.asList(
new CoffeeSales(LocalDate.of(2024, 3, 1), "Latte", "cash", 1, 6.26),
new CoffeeSales(LocalDate.of(2024, 3, 5), "Hot Chocolate", "card", 3, 32.51),
new CoffeeSales(LocalDate.of(2024, 3, 6), "Americano", "card", 2, 18.70));
DescriptiveStatistics stats = new DescriptiveStatistics();
sales.forEach(sale -> stats.addValue(sale.amount()));
System.out.printf("\nSales analyzed: %d%n", sales.size());
// Compute the mean transaction amount
System.out.printf("Average amount: $%.2f%n", ____.____());
// Compute the min and max transaction amounts
System.out.printf("Amount range: $%.2f - $%.2f%n",
____.____(), ____.____());
}
}