開始使用免費開始

安全讀取 CSV 檔案

你已經可以讀取一個咖啡銷售的 CSV 檔案。請使用資料驗證函式讀取資料,並驗證各欄位的資料型別。

所需的套件(例如 java.timeNumberUtils)已經為你匯入。

本練習屬於課程

使用 Java 進行資料清理

檢視課程

練習說明

  • 將日期字串的格式解析為 M/d/yy
  • 將銷售的 quantity 讀取為 Integer

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class CoffeeSalesExample {
    private record CoffeeSales(LocalDate date, String coffeeName, String paymentMethod, Integer quantity, Double amount) {}

    private static LocalDate parseDate(String dateStr) {
    	// Parse the format of the date string
        return ____.____(dateStr, DateTimeFormatter.ofPattern("M/d/yy"));
    }

    private static String validateNumeric(String value) {
        if (NumberUtils.isParsable(value)) return value;
        throw new IllegalArgumentException("Invalid: " + value);
    }
    
    public static double parsePrice(String priceText) {
        if (NumberUtils.isParsable(priceText.replace("$", ""))) {
            return Double.parseDouble(priceText.replace("$", ""));
        }
        throw new IllegalArgumentException("Invalid price: " + priceText);
    }

    public static CoffeeSales parseSalesData(String[] fields) {
        LocalDate publishDate = parseDate(fields[0]);
        String coffeeName = fields[1];
        String paymentMethod = fields[2];
        // Read quantity as an Integer
        Integer quantity = ____.____(validateNumeric(fields[3]));
        Double amount = parsePrice(fields[4]);
        return new CoffeeSales(publishDate, coffeeName, paymentMethod, quantity, amount);
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        List sales = new ArrayList<>();
        String filename = "coffee.csv";
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line = reader.readLine();
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split(",");
                sales.add(parseSalesData(fields));
            }
        }
        sales.forEach(System.out::println);
    }
}
編輯並執行程式碼