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.
Este exercício faz parte do curso
Cleaning Data in Java
Instruções do exercício
- Print the violation message when the data violates a constraint.
- Validate the video game sale by applying the
validator
.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
import java.util.Set;
import jakarta.validation.*;
import jakarta.validation.constraints.*;
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);
}
}