開始使用免費開始

將文字解析為日期與數字

你正在準備驗證咖啡店銷售資料的資料型別。請在範例資料上設定檢查日期與數字的函式。

必要的套件(如 DateTimeFormatterNumberUtils)已為你匯入。

本練習屬於課程

使用 Java 進行資料清理

檢視課程

練習說明

  • 將資料的日期格式指定為 M/d/yy
  • 將交易金額解析為 Double。
  • 檢查交易金額是否能被解析為數字。

動手互動練習

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

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);
    }
}
編輯並執行程式碼