Annotation กับข้อมูลยอดขายวิดีโอเกม
ต้องการตรวจสอบความถูกต้องของข้อมูลยอดขายวิดีโอเกมเพื่อตรวจจับข้อผิดพลาดในข้อมูล ตัวอย่างข้อมูลแสดงไว้ด้านล่าง กำหนด annotation ให้กับ attribute ของคลาส VideoGameSale เพื่อตรวจสอบว่าฟิลด์ไม่ว่างเปล่า และค่าของฟิลด์เป็นไปตามเงื่อนไขที่กำหนด
| name | platform | year | sales |
|---|---|---|---|
| Wii Sports | Wii | 2006 | 41.49 |
| Super Mario Bros. | NES | 1985 | 29.08 |
| Mario Kart Wii | Wii | 2008 | 15.85 |
ได้ import package jakarta.validation.constraints ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำความสะอาดข้อมูลใน Java
คำแนะนำการฝึกหัด
- เพิ่ม annotation เพื่อตรวจสอบว่า
nameและplatformไม่ว่างเปล่า - ตรวจสอบว่า
yearมีค่าอย่างน้อย 1960 - ตรวจสอบว่า
salesเป็นจำนวนบวก
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
public class VideoGameSale {
// Check that name is not empty
@____(message = "Name cannot be empty")
private String name;
// Check that platform is not empty
@____(message = "Platform cannot be empty")
private String platform;
// Check that year is at least 1960
____(value = ____, message = "Year must be greater than 1960")
private Integer year;
// Check that sales is positive
____(value = ____, message = "Sales amount must be positive")
private Double sales;
public static void main(String[] args) {
System.out.println("Nice job setting up the annotations!");
}
}