시작하기무료로 시작하기

Reading CSV files safely

You're ready to read a CSV file of coffee sales. Use data validation functions to read in the data and validate the data types.

The necessary packages such as java.time, and NumberUtils have been imported for you.

이 연습은 강의의 일부입니다

Cleaning Data in Java

강의 보기

연습 안내

  • Parse the format of the date string as M/d/yy.
  • Read the sales quantity as an 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);
    }
}
코드 편집 및 실행