BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Cleaning Data in Java

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • Print the violation message when the data violates a constraint.
  • Validate the video game sale by applying the validator.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

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);
    }
}
Kodu Düzenle ve Çalıştır