2016-10-16 3 views
0

Методы setDates и setTimes имеют в качестве предварительных условий, что ни один из их аргументов не равен нулю. Это должно быть проверено с помощью утверждения. (Это означает, что, если предварительное условие не выполняется, то программа потерпит неудачу в утверждении, и AssertionError будет выброшено.)Проверка с утверждением

вот мой код:

public class Section 
{ 
/** 
* Default section number. 
*/ 
private static final String DEFAULT_SECTION_NUMBER = ""; 

/** 
* Constant for building Strings with newline characters within them. 
*/ 
private static final String LINE_SEPARATOR = System. 
     getProperty("line.separator"); 

/** 
* The maximum number of students permitted into a section. 
*/ 
private static final int MAXIMUM_STUDENTS_PER_SECTION = 30; 

/** 
* Valid length for a sectionNumber string. 
*/ 
private static final int SECTION_NUMBER_LENGTH = 3; 

/** 
* Shared variable for keeping count of the number of section objects in 
* existence. 
*/ 
private static int count = 0; 

/** 
* The date at which the section is finished. 
*/ 
private Date endDate; 

/** 
* The end time for the meeting of the section. 
*/ 
private Time2 endTime; 

/** 
* The list of students in the class. This declaration uses the Java 7 facility 
* of not repeating the generic type if that type can be inferred by the 
* compiler. 
*/ 
private final List<Student> roster = new ArrayList<>(); 

/** 
* The three-character designation of the section (called a 
* &ldquo;number&rdquo;). 
*/ 
private String sectionNumber = DEFAULT_SECTION_NUMBER; 

/** 
* The date on which the section starts to meet. 
*/ 
private Date startDate; 

/** 
* The time of day at which the section meets. 
*/ 
private Time2 startTime; 

/** 
* The course of which this is a section. 
*/ 
private final Course thisCourse; 

/** 
* Constructor. 
* 
* @param course  the course of which this is a section 
* @param sectionNumber the section number (within the course) of this section 
* @throws SectionException 
*/ 
public Section(Course course, String sectionNumber) throws SectionException 
{ 
    /* Increment the collective count of all Section objects that have been 
     created. Do this first as the object already exists. */ 
      ++count; 

       this.thisCourse = course; 
      try 
      { 
       if(isValidSectionNumber(sectionNumber)) 
       this.sectionNumber = sectionNumber; 
      } 
      catch (Exception ex) 
      { 
       throw new SectionException("Error in constructor", ex); 
      } 
} 

/** 
* Add a student to the course. 
* 
* @param student the student object to be added. If the course is full, the 
*     student is not added 
*/ 
public void addStudent(Student student) 
{ 
    if(roster.size() != MAXIMUM_STUDENTS_PER_SECTION) 
     roster.add(student); 
} 

/** 
* Get details about the current state of this section, including the course of 
* which it is part, the dates it starts and ends, times, etc., and the current 
* count of the enrollment. 
* 
* @return the section details 
*/ 
public String getDetails() 
{ 
    return String.join(LINE_SEPARATOR, 
      "Section: " + this.toString(), 
      "Course: " + thisCourse.getDetails(), 
      "Dates: " + startDate + " to " + endDate, 
      "Times: " + startTime + " to " + endTime, 
      "Enrollment: " + roster.size()); 
} 

/** 
* Create a string that represents the information about the students in the 
* course. 
* 
* @return  a string that represents the information about the students in the 
*    course 
*/ 
public String getRoster() 
{ 
    /* The following commented-out code is the obvious way to do this, using 
     String concatenation (and this is acceptable). However, the recommended 
     Java approach to this kind of operation is to use a StringJoiner (new 
     class in Java 8), as this uses less garbage collection resources. */ 
// String result = ""; 
// for(Student student : roster) 
// { 
//  result += (result.isEmpty() ? "" : LINE_SEPARATOR) + student; 
// } 
// return result; 

    StringJoiner stringJoiner = new StringJoiner(LINE_SEPARATOR); 
    for(Student student : roster) 
     stringJoiner.add(student.toString()); 
    return stringJoiner.toString(); 
} 

/** 
* Get a count of the number of students registered (on the roster) for this course. 
* 
* @return a count of the number of students registered for this course 
*/ 
public int getRosterCount() 
{ 
    return roster.size(); 
} 

/** 
* Get the section number for this course. 
* 
* @return the section number for this course 
*/ 
public String getSectionNumber() 
{ 
    return sectionNumber; 
} 

/** 
* Set the start and end dates for the section. 
* 
* @param startDate  the start date 
* @param endDate  the end date 
*/ 
public void setDates(Date startDate, Date endDate) 
{ 
    /* There is no requirement to validate these. */ 
    this.startDate = startDate; 
    this.endDate = endDate; 
} 

/** 
* Set the start time and the end time for the meetings of the section. 
* 
* @param startTime  the start time for meetings of the section 
* @param endTime  the end time for the meetings of the section 
*/ 
public void setTimes(Time2 startTime, Time2 endTime) 
{ 
    /* There is no requirement to validate these. */ 
    this.startTime = startTime; 
    this.endTime = endTime; 
} 

/** 
* Section number (prefixed) 
* 
* @return Section number (prefixed) 
*/ 
@Override 
public String toString() 
{ 
    return thisCourse.toString() + "-" + sectionNumber; 
} 

/** 
* Finalization. Reduce the instance count by 1. 
* 
* @throws Throwable standard interface. 
*/ 
@SuppressWarnings("FinalizeDeclaration") 
@Override 
protected void finalize() throws Throwable 
{ 
    /* Decrement the count of the collective total of all Section objects. */ 
    --count; 
    super.finalize(); 
} 

/** 
* Get a count of how many total Section objects are currently in existence. 
* 
* @return a count of how many Section objects are currently in existence 
*/ 
public static int getSectionCount() 
{ 
    return count; 
} 

/** 
* Validate the sectionNumber string. It must be of the correct length. 
* 
* @param sectionNumber the sectionNumber string 
* @return    true if the string if valid, otherwise false 
*/ 
private static boolean isValidSectionNumber(String sectionNumber) 
{ 
    return sectionNumber != null && 
      sectionNumber.length() == SECTION_NUMBER_LENGTH; 
} 
} 

бы я просто поместить «утверждать» до this.startDate = startDate; и так далее??? моя книга имеет только один пример, и для обеспечения значение между 0 и 10.

это пример моя книга использует:

public class AssertTest 
{ 
public static void main(string[] args) 
{ 
Scanner input = new Scanner(System.in); 

System.out.print("Enter a number between 0 and 10: "); 
int number = input.nextInt(); 

//assert that the value is >= 0 and <= 10 
assert (number >= 0 && number <= 10) : "bad number: " + number; 

System.out.printf("You entered %d%n", number); 
} 
} 

так я мог сказать

assert this.startDate = startDate 
assert this.endDate = endDate 

и скоро?

ответ

0

Прежде всего методы setTime и setDates являются общедоступными, что позволяет предположить, что они могут использоваться вне пакета. Учитывая, что вы не контролируете параметры - использование assert не считается лучшей практикой. Вы должны лучше использовать среды выполнения исключений, таких как IllegalArgumentException, когда значение может подаваться извне (и вы не имеете никакого контроля над ним):

if (startDate == null || endDate == null) 
    throw new IllegalArgumentException("Non-null arguments are required"); 

Синтаксис Assert будет выглядеть следующим образом:

assert startDate != null; 
assert endDate != null; 

You также может использовать следующий синтаксис для вывода дополнительной информации при сбое утверждения:

assert startDate != null : "startDate was set to null" 
assert endDate != null : "endDate was set to null"