开始使用免费开始使用

显示校验信息

您已经使用注解为视频游戏销售数据设置了质量控制。现在请在包含错误的数据上运行校验,看看会打印出哪些信息。这些不合规数据缺少 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);
    }
}
编辑并运行代码