Question

In: Computer Science

Define and implement class Course. This class should contain the following fields: course name, course description,...

Define and implement class Course. This class should contain the following fields: course name, course description, department, time the course starts, weekday the course is held on (for simplicity, let us assume the course only meets once a week). This class should contain getters and setters for all its attributes. This class also needs at least one constructor. Save this class and its definition into a file named Course.java.

Define and implement class Student. This class should contain the following fields: first name, last name, age, gpa, major, department, courses. Age should be an integer value. GPA should be a floating point value. Courses should be a linked list of Course variables. Class Student should contain getters and setters for all its attributes. This class also needs at least one constructor. In class Student implement the following methods: addCourse() to add a new course, removeCourse() to remove a course from this student, sortCourses() to print out a sorted list of courses. Method sortCourses() should accept parameters to specify whether the sorting should be ascending or descending and also based on which course attribute to sort the courses. The output should be printed to command line standard output. Save this class and its definition into a file named Student.java.

Solutions

Expert Solution

Course.java

class Course {
        private String courseName;
        private String courseDescription;
        private String department;
        // assuming format YYYY-MM-DD for easier sorting
        private String courseStartTime;
        private String weekday;

        public Course() {}

        public Course(String courseName, String courseDescription, String department, String courseStartTime, String weekday) { 
                this.courseName = courseName;
                this.courseDescription = courseDescription;
                this.department = department;
                this.courseStartTime = courseStartTime;
                this.weekday = weekday;
        }

        public String getCourseName() {
                return courseName;
        }

        public String getCourseDescription() {
                return courseDescription;
        }

        public String getDepartment() {
                return department;
        }

        public String getStartTime() {
                return courseStartTime;
        }

        public String getDay() {
                return weekday;
        }

        public void setCourseName(String courseName) {
                this.courseName = courseName;
        }

        public void setCourseDescription(String courseDescription) {
                this.courseDescription = courseDescription;
        }

        public void setDepartment(String department) {
                this.department = department;
        }

        public void setStartTime(String courseStartTime) {
                this.courseStartTime = courseStartTime;
        }

        public void setDay(String weekday) {
                this.weekday = weekday;
        }

        @Override
        public String toString() {
        // print the course object as defined below 
                return "{{\"Course\": " + courseName + "}, {\"Description\": " + courseDescription + "}, {\"Department\": " + 
                department + "}, {\"Start Time\": " + courseStartTime + "}, {\"Day\": " + weekday + "}}"; 
        }
}

Student.java

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.HashMap;

class Student {
        private String firstName;
        private String lastName;
        private int age;
        private float gpa;
        private String major;
        private String department;
        LinkedList<Course> enrollments;

        public Student() {
                enrollments = new LinkedList<Course>();
        }

        public Student(String firstName, String lastName, int age, float gpa, String major, String department) {
                // this() calls the non-parametrized constructor which initializes the linked list
        this();
                this.firstName = firstName;
                this.lastName = lastName;
                this.age = age;
                this.gpa = gpa;
                this.major = major;
                this.department = department;
        }

        public String getFirstName() {
                return firstName;
        }

        public String getLastName() {
                return lastName;
        }

        public int getAge() {
                return age;
        }

        public float getGPA() {
                return gpa;
        }

        public String getMajor() {
                return major;
        }

        public String getDepartment() {
                return department;
        }

        public LinkedList<Course> getCourseEnrollments() {
                return enrollments;
        }

        public void setFirstName(String firstName) {
                this.firstName = firstName;
        }

        public void setLastName(String lastName) {
                this.lastName = lastName;
        }

        public void setAge(int age) {
                this.age = age;
        }

        public void setGPA(float gpa) {
                this.gpa = gpa;
        }

        public void setMajor(String major) {
                this.major = major;
        }

        public void setDepartment(String department) {
                this.department = department;
        }

        public void addCourse(Course course) {
        // do nothing if the linked list already contains the course
                if(!enrollments.contains(course)) {
                        enrollments.add(course);
                }
        }

        public void removeCourse(Course course) {
        // course can be removed only if it is present
                if(enrollments.contains(course)) {
                        enrollments.remove(course);
                }
        }

        public void sortCourses(String attribute, boolean sortDescending) {

        // dayMapping is used below to sort when sorted using day of the week
        // i.e. on sorting by day in ascending order, courses starting on Monday should come before courses starting on Wednesday for e.g.
        // hence we will use the value corresponding to the day for sorting
                HashMap<String, Integer> dayMapping = new HashMap<String, Integer>();
                dayMapping.put("Sunday", 0);
                dayMapping.put("Monday", 1);
                dayMapping.put("Tuesday", 2);
                dayMapping.put("Wednesday", 3);
                dayMapping.put("Thursday", 4);
                dayMapping.put("Friday", 5);
                dayMapping.put("Saturday", 6);
                 
        // define how to sort the linked list by overriding the compare() method
                Collections.sort(enrollments, new Comparator<Course>() {
                        @Override
                        public int compare(Course o1, Course o2) {
                // sorting depending on the attribute specified
                                switch(attribute) {
                                        case "name":
                        // course names are strings
                        // compareTo is a Java string method for comparing strings
                                                return o1.getCourseName().compareTo(o2.getCourseName());
                                        case "department":
                                                return o1.getDepartment().compareTo(o2.getDepartment());
                                        case "time":
                                                return o1.getStartTime().compareTo(o2.getStartTime());
                                        case "day":
                                                return (dayMapping.get(o1.getDay()) - 
                                dayMapping.get(o2.getDay()));
                                        default:
                        // the default sorting behavior is based on course name
                                                return o1.getCourseName().compareTo(o2.getCourseName());
                                }
                        }
                });
        // reverse the resultant linked list if sorting in descending order was required
                if(sortDescending) {
                        Collections.reverse(enrollments);
                }

        // print the list of courses
                for(Course c : enrollments) {
                        System.out.println(c);
                }
        }
}

Tester.java

public class Tester {
        public static void main(String[] args) {
                Course course = new Course("DSA-101", "Introduction to Algorithms", "CSED", "2020-10-19", "Monday");
                Course course2 = new Course("OOM-101", "Object Oriented Modelling", "CSED", "2020-10-21", "Wednesday");
                Course course3 = new Course("ST-101", "Statistics", "CSED", "2020-10-16", "Friday");
                Student student = new Student("John", "Doe", 21, 3.5f, "CS", "CSED");
                student.addCourse(course);
                student.addCourse(course2);
                student.addCourse(course3);
                student.sortCourses("time", true);
        System.out.println("\n");
                student.sortCourses("day", false);
        }       
}

Sample Output (Corresponding to code in Tester.java).


Related Solutions

Design a class named Pet, which should have the following fields: Name – The name field...
Design a class named Pet, which should have the following fields: Name – The name field holds the name of a pet. Type – The type field holds the type of animal that is the pet. Example values are “Dog”, “Cat”, and “Bird”. Age – The age field holds the pet’s age. The Pet class should also have the following methods: setName – The setName method stores a value in the name field. setType – The setType method stores a...
Question1: Define a class Human that contains: - The data fields "first name" and "last name"...
Question1: Define a class Human that contains: - The data fields "first name" and "last name" - A constructor that sets the first and last name to the instance variables. Create also a no-argument constructor - A getName() method which prints the first and last name Define the class Student which inherits Human and contains: - Private data field "mark" of type integer and a constructor which calls the superclass constructor Define the class Worker which inherits Human and contains:...
Create a class named GameCharacter to define an object as follows: The class should contain class...
Create a class named GameCharacter to define an object as follows: The class should contain class variables for charName (a string to store the character's name), charType (a string to store the character's type), charHealth (an int to store the character's health rating), and charScore (an int to store the character's current score). Provide a constructor with parameters for the name, type, health and score and include code to assign the received values to the four class variables. Provide a...
           Homework: Polynomial Using Array Description: Implement a polynomial class (1) Name your class...
           Homework: Polynomial Using Array Description: Implement a polynomial class (1) Name your class Polynomial (2) Use array of doubles to store the coefficients so that the coefficient for x^k is stored in the location [k] of the array. (3) define the following methods: a. public Polynomial()    POSTCONDITION: Creates a polynomial represents 0 b. public Polynomial(double a0)    POSTCONDITION: Creates a polynomial has a single x^0 term with coefficient a0 c. public Polynomial(Polynomial p)    POSTCONDITION: Creates...
Goals Understand class structure and encapsulation Description Define a class Product to hold the name and...
Goals Understand class structure and encapsulation Description Define a class Product to hold the name and price of items in a grocery store. Encapsulate the fields and provide getters and setters. Create an application for a grocery store to calculate the total bill for each customer. Such program will read a list of products purchased and the quantity of each item. Each line in the bill consists of: ProductName ProductPrice Quantity/Weight The list of items will be terminated by “end”...
For a supermarket, define a Inventory class. All the Inventory objects will contain S,No, name of...
For a supermarket, define a Inventory class. All the Inventory objects will contain S,No, name of clerk preparing the inventory, each item with id, quantity available , minimum order quantity ,price and date of expiry. There is an array to describe the above details. Your program generate the stock based on the items quantity is equal to minimum order quantity or less than minimum order quantity and also display items to check date of expiry with current date.
Implement an Employee class that includes data fields to hold the Employee’s ID number, first name,...
Implement an Employee class that includes data fields to hold the Employee’s ID number, first name, last name, and hourly pay rate (use of string datatype is not allowed). Create an array of five Employee objects. Input the data in the employee array. Write a searchById() function, that ask the user to enter an employee id, if its present, your program should display the employee record, if it isn’t there, simply print the message ”Employee with this ID doesn’t exist”....
In Java...create a class Realestate.java with the following fields: location, price, and description. Create a class...
In Java...create a class Realestate.java with the following fields: location, price, and description. Create a class RealestateFinder.java that reads in real estate data from a CSV file (RealestateList.csv). Then provide the user with the following options: Sort per Price, Sort per Location, and Exit. Use ArrayList and Arrays.sort to perform the sorts and display the data to the user.
1. Circle: Implement a Java class with the name Circle. It should be in the package...
1. Circle: Implement a Java class with the name Circle. It should be in the package edu.gcccd.csis. The class has two private instance variables: radius (of the type double) and color (of the type String). The class also has a private static variable: numOfCircles (of the type long) which at all times will keep track of the number of Circle objects that were instantiated. Construction: A constructor that constructs a circle with the given color and sets the radius to...
Define a class to represent a Temperature. Your class should contain Instance variable int fahrenheit A...
Define a class to represent a Temperature. Your class should contain Instance variable int fahrenheit A parameterized constructor; Member method to calculate the equivalent temperature in Celsius unit toCelsius() with decimal value. double toCelsius() Conversion formula: celsius= (fahrenheit - 32) * 5/9 Method definition to override the equals() method boolean equals(Object obj)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT