시작하기무료로 시작하기

Displaying validation messages

You have set up annotations as quality control on video game sales data. Now try running the validation on data with mistakes to see what messages are printed. The bad data is missing a platform, has year before 1960, and has negative sales, which violates the constraints specified in the annotations. Validate the video game sales data and print any violation messages.

jakarta packages have been imported for you.

이 연습은 강의의 일부입니다

Cleaning Data in Java

강의 보기

연습 안내

  • Print the violation message when the data violates a constraint.
  • Validate the video game sale by applying the 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);
    }
}
코드 편집 및 실행