LoslegenKostenlos loslegen

Parsing text into dates and numbers

You're preparing to validate the data types in the coffee shop sales. Set up the functions to check dates and numbers on sample data.

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

Diese Übung ist Teil des Kurses

Cleaning Data in Java

Kurs anzeigen

Anleitung zur Übung

  • Specify the date format for the data as M/d/yy.
  • Parse the transaction amount as a Double.
  • Check if the transaction amount can be parsed as a number.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

public class CoffeeSalesExample {
    private static LocalDate parseDate(String dateStr) {
        // Specify the date format for the data
        DateTimeFormatter format = ____.____("M/d/yy");
        return LocalDate.parse(dateStr, format);
    }
    
    private static double parseAmount(String amount) {
        // Parse the amount as a Double
        return ____.____(amount.replace("$", "").trim());
    }

    public static void main(String[] args) {        
        LocalDate date = parseDate("1/10/23");
        System.out.println("Date: " + date);
        
        String amount = "$30.61";
        // Check if the amount can be parsed as a number
        boolean isAmountParsable = ____.____(amount);
        System.out.println("Is amount parsable? " + isAmountParsable);
        
        Double parsedAmount = parseAmount(amount);
        System.out.println("parsedAmount: " + parsedAmount);
    }
}
Code bearbeiten und ausführen