การแปลงข้อความเป็นวันที่และตัวเลข
เตรียมตรวจสอบชนิดข้อมูลในยอดขายของร้านกาแฟ โดยตั้งค่าฟังก์ชันสำหรับตรวจสอบวันที่และตัวเลขด้วยข้อมูลตัวอย่าง
แพ็กเกจที่จำเป็น เช่น DateTimeFormatter และ NumberUtils ได้รับการนำเข้าให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำความสะอาดข้อมูลใน 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);
}
}