Question

1. Do the following a. Write a class Student that has the following attributes: - name:...

1. Do the following

a. Write a class Student that has the following attributes:
- name: String, the student's name ("Last, First" format)
- enrollment date (a Date object)

The Student class provides a constructor that saves the student's name and enrollment date.

Student(String name, Date whenEnrolled)

The Student class provides accessors for the name and enrollment date.


Make sure the class is immutable. Be careful with that Date field -- remember what to do when sharing mutable instance variables -- issued discussed in Chapter 3 (class Employee).

Write contracts for all methods: preconditions/postconditions. Write the class invariant in the class javadoc comment.

b. Implement a static method in class Student

public static Comparator<Student> getCompByName()

that returns a new comparator object for Student that compares 2 Students objects by the attribute 'name'.

Implement a static method in class Student

public static Comparator<Student> getCompByDate()

that returns a new comparator object for Student that compares 2 Students objects by their enrollment date.

You must use anonymous classes that implement the Comparator interface.


c. Write a public static main() method in class Student that:
- creates an ArrayList<Student> object called students
- adds 4 new Student objects to the students list, with some made up names and dates
- sort the students list by name and display the sorted collection to System.out. use function getCompByName()
- sort the students list by enrollment date and display the sorted collection to System.out. use function getCompByDate()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.Comparator;
import java.util.Date;

public final class Student {

   private final String name;
   private final Date enrollment_date;

   /*@invariant name != null && name.length>0; @*/ //class invariant
/*@invariant enrollment_date != null; @*/ //class invariant
   public Student(String name, Date enrollment_date) {
       super();
      
       assert name != null : "Precondition: name != null";
       assert enrollment_date != null : "Precondition: enrollment_date != null";
       assert name.indexOf(",") != -1 : "Precondition: name.indexOf(\",\") != -1";
      
       this.name = name;
       this.enrollment_date = enrollment_date;
      
       assert getName() == name : "Postcondition: getName() == name";
       assert getEnrollment_date() == enrollment_date : "Postcondition: getEnrollment_date() == enrollment_date";
   }

   public String getName() {
       return name;
   }

   public Date getEnrollment_date() {
       return enrollment_date;
   }

   public static Comparator<Student> getCompByName =
           new Comparator<Student>(){

       @Override
       public int compare(Student o1, Student o2) {

           assert o1.name != null : "Precondition: o1.name != null";
           assert o2.name != null : "Precondition: o2.name != null";
          
           return o1.name.compareTo(o2.name);
       }

   };

   public static Comparator<Student> getCompByDate =
           new Comparator<Student>(){

       @Override
       public int compare(Student p, Student q) {

           if (p.getEnrollment_date().before(q.getEnrollment_date())) {
               return -1;
           } else if (p.getEnrollment_date().after(q.getEnrollment_date())) {
               return 1;
           } else {
               return 0;
           }
       }

   };

}

Add a comment
Know the answer?
Add Answer to:
1. Do the following a. Write a class Student that has the following attributes: - name:...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Ini...

    Must be in Python 3 exercise_2.py # Define the Student class class Student():    # Initialize the object properties def __init__(self, id, name, mark): # TODO # Print the object as an string def __str__(self): return ' - {}, {}, {}'.format(self.id, self.name, self.mark) # Check if the mark of the input student is greater than the student object # The output is either True or False def is_greater_than(self, another_student): # TODO # Sort the student_list # The output is the sorted...

  • Question 1 (24 Marks] 1. (4 marks) Write an immutable Person class in Java which provides...

    Question 1 (24 Marks] 1. (4 marks) Write an immutable Person class in Java which provides the following. • Two attributes: lastName and first Name of type String. • Appropriate initialization, accessors/mutator methods. 2. (6 marks) Write a Student class that is a subclass of Person class (in the previous question) which provides the following. • Two attributes: A unique student ID of type String and GPA of type float; the student ID is initialized when a Student object gets...

  • I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student...

    I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student {    private String name;    private double gpa;    private int idNumber;    public Student() {        this.name = "";        this.gpa = 0;        this.idNumber = 0;    }    public Student(String name, double gpa, int idNumber) {        this.name = name;        this.gpa = gpa;        this.idNumber = idNumber;    }    public Student(Student s)...

  • Start a new project in NetBeans that defines a class Person with the following: Instance variables...

    Start a new project in NetBeans that defines a class Person with the following: Instance variables firstName (type String), middleInitial (type char) and lastName (type String) (1) A no-parameter constructor with a call to the this constructor; and (2) a constructor with String, char, String parameters (assign the parameters directly to the instance variables in this constructor--see info regarding the elimination of set methods below) Accessor (get) methods for all three instance variables (no set methods are required which makes...

  • In Java programming language Please write code for the 6 methods below: Assume that Student class...

    In Java programming language Please write code for the 6 methods below: Assume that Student class has name, age, gpa, and major, constructor to initialize all data, method toString() to return string reresentation of student objects, getter methods to get age, major, and gpa, setter method to set age to given input, and method isHonors that returns boolean value true for honors students and false otherwise. 1) Write a method that accepts an array of student objects, and n, the...

  • Given a class called Student and a class called Course that contains an ArrayList of Student....

    Given a class called Student and a class called Course that contains an ArrayList of Student. Write a method called getDeansList() as described below. Refer to Student.java below to learn what methods are available. I will paste both of the simple .JAVA codes below COURSE.JAVA import java.util.*; import java.io.*; /****************************************************** * A list of students in a course *****************************************************/ public class Course{     /** collection of Students */     private ArrayList<Student> roster; /***************************************************** Constructor for objects of class Course *****************************************************/...

  • Create a java project and create Student class. This class should have the following attributes, name...

    Create a java project and create Student class. This class should have the following attributes, name : String age : int id : String gender : String gpa : double and toString() method that returns the Student's detail. Your project should contain a TestStudent class where you get the student's info from user , create student's objects and save them in an arralist. You should save at least 10 student objects in this arraylist using loop statement. Then iterate through...

  • Write a class called Student. The specification for a Student is: Three Instance fields name -...

    Write a class called Student. The specification for a Student is: Three Instance fields name - a String of the student's full name totalQuizScore - double numQuizesTaken - int Constructor Default construtor that sets the instance fields to a default value Parameterized constructor that sets the name instance field to a parameter value and set the other instance fields to a default value. Methods setName - sets or changes the student name by taking in a parameter getName - returns...

  • In Java Create an array of Student objects. Display the students by age in UNSORTED order....

    In Java Create an array of Student objects. Display the students by age in UNSORTED order. Apply the Quick sort and Display the students by age in SORTED order. public class TestQuickStudent { public static void main (String [ ] args ) { /* ***Create your array of Student objects with AT LEAST 5 names */ System.out.println ( " ____________________________");    /* ***LOOP through your array and print out each UNSORTED check by student age */ System.out.println ( " ____________________________");...

  • Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use impl...

    Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use implements Comparable<Book> in the class definition. Now, all book objects are instances of the java.lang.Comparable interface. Write a test program that creates an array of ten books. 1. Use Arrays.sort( Book[]l books) from the java.util package to sort the array. The order of objects in the array is determined using compareTo...) method. 2. Write a method that returns the most expensive book in the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT