開始使用免費開始

顯示驗證訊息

你已經用註解為電玩遊戲的銷售資料設置了品質管控。現在請嘗試在含有錯誤的資料上執行驗證,看看會印出哪些訊息。這筆不良資料缺少 platformyear 早於 1960,且 sales 為負值,這些都違反了註解中指定的限制條件。請驗證這筆電玩遊戲的銷售資料,並印出任何違規訊息。

已為你匯入 jakarta 套件。

本練習屬於課程

使用 Java 進行資料清理

檢視課程

練習說明

  • 當資料違反限制條件時,印出違規訊息。
  • 套用 validator 來驗證這筆電玩遊戲的銷售資料。

動手互動練習

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

public class VideoGameSale {
    @NotNull(message = "Name cannot be empty")
    private String name;
    @NotNull(message = "Platform cannot be empty")
    private String platform;
    @Min(value = 1960, message = "Year must be greater than 1960")
    private Integer year;
    @Min(value = 0, message = "Sales amount must be positive")
    private Double sales;

    public VideoGameSale(String name, String platform, Integer year, Double sales) {
        this.name = name;
        this.platform = platform;
        this.year = year;
        this.sales = sales;
    }

    public static void main(String[] args) {
        VideoGameSale sale = new VideoGameSale(
                "Super Mario Bros.", null, 1950,
                -29.08);
        Set> violations =
                SalesValidator.validateSale(sale);
        // Print the violation message
        violations.forEach(violation ->
                System.out.println(____.____()));
        if (!violations.isEmpty()) throw new ConstraintViolationException(violations);
    }
}

class SalesValidator {
    private static final ValidatorFactory factory =
          Validation.buildDefaultValidatorFactory();
    private static final Validator validator = factory.getValidator();
    public static Set> validateSale(VideoGameSale sale) {
        // Validate the video game sale
        return ____.____(sale);
    }
}
編輯並執行程式碼