ArrayList验证错误

时间:2017-01-29 20:06:13

标签: java validation exception arraylist

我尝试使用do ... while循环向对象添加ArrayList。不幸的是,每次运行程序时,我都会继续收到验证错误。

这是我用来将ArrayList添加到对象DVD的函数:

    public DVD getNewDVDInfo() {

    String title = io.readString("Please enter DVD title");
    String releaseDate = io.readString("Please enter Release Date (mm-DD-yyyy)");
    LocalDate ld = LocalDate.parse(releaseDate, DateTimeFormatter.ofPattern("mm-DD-yyyy"));
    String mpaaRating = io.readString("Please enter MPAA Rating");
    String directorName = io.readString("Please enter Director's Name");
    String studio = io.readString("Please enter Studio");
    boolean hasNext = true;
    ArrayList<String> userRating = new ArrayList<>();
    String userRatingString = io.readString("Please enter User Rating");

    userRating.add(userRatingString);
    DVD currentDVD = new DVD(title);
    currentDVD.setReleaseDate(ld);
    currentDVD.setMpaaRating(mpaaRating);
    currentDVD.setDirectorName(directorName);
    currentDVD.setStudio(studio);
    currentDVD.setUserRating(userRating);

    return currentDVD;
}

验证方法:

    private void validateDVDData(DVD dvd) throws DVDLibraryDataValidationException {
    if (dvd.getTitle() == null || dvd.getTitle().trim().length() == 0
            || dvd.getReleaseDate() == null
            || dvd.getMpaaRating() == null || dvd.getMpaaRating().trim().length() == 0
            || dvd.getDirectorName() == null || dvd.getDirectorName().trim().length() == 0
            || dvd.getStudio() == null || dvd.getStudio().trim().length() == 0
            || dvd.getUserRating()== null || dvd.getUserRating().isEmpty()); {

        throw new DVDLibraryDataValidationException("ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name, Studio, User Rating] are required");
    }
}

每次运行应用程序时,都会抛出错误消息。 任何帮助将非常感激。

1 个答案:

答案 0 :(得分:0)

要确定您的问题,您可以使用调试器,但您也可以改进检查的方式。
而不是做一个全局错误:

  

错误:所有字段[标题,发布日期,MPAA评级,主管姓名,   工作室,用户评级]是必需的&#34;);

对用户(以及跟踪信息的跟踪)更有帮助,以了解提供的值中的问题究竟在哪里。

DVDLibraryDataValidationException课程中,您可以添加String字段列表,添加错误字段名称。
您可以覆盖此类的getMessage()以提供有用的消息,指示包含验证错误的字段。

只是想知道如何开始:

List<String> errorFields = new ArrayList<>();
 if (dvd.getTitle() == null || dvd.getTitle().trim().length() == 0){
    errorFields.add("title");
 }

 if (dvd.getReleaseDate() == null ){
    errorFields.add("release date");
 }
 ...
 if (!errorFields.isEmpty()){
    throw new DVDLibraryDataValidationException("ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name, Studio, User Rating] are required", 
                                                 errorFields);
 }