การคำนวณค่าเฉลี่ย ค่าต่ำสุด และค่าสูงสุด
สมมติว่าต้องการวิเคราะห์ข้อมูลยอดขายของธุรกิจกาแฟ ชุดข้อมูลประกอบด้วยวันที่ทำรายการ ชื่อกาแฟ วิธีชำระเงิน จำนวนที่ขาย และยอดรายการ ดังตัวอย่างด้านล่าง ให้คำนวณค่าเฉลี่ย ค่าต่ำสุด และค่าสูงสุดของยอดรายการ โดยแสดงผลทศนิยม 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 ได้ถูก import ไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำความสะอาดข้อมูลใน 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",
____.____(), ____.____());
}
}