• Write a class Course of java A course has a department code (e.g., CPS or MATH
ID: 3596276 • Letter: #
Question
• Write a class Course of java
A course has a department code (e.g., CPS or MATH), a course number, and a room number.
– Include a static variable used to assign the course number to each Course in the constructor. The value of the variable will start at 2000.
– Write the instance variables, the accessors (getters), the mutators (setters) and two constructors for the class. One of the constructors should be the no args constructor
– Also write a toString() method that returns all of the instance variables strung together appropriately (e.g., “Dept: CPS; CourseNumber: 2000; Room 208”)
– Create an Array of Course objects which can hold 3 elements.
– Using a loop:
• Ask the user for the name, department and room number for 3 course depts and room numbers.
• TIP: Use next() instead of nextLine()
• Create course objects.
• Store the objects in the Array – At the end, traverse the array of courses and print each course on a separate line.
Sample output
Enter Dept
CPS
Enter room number
208
Enter Dept
CPS
Enter room number
220
Enter Dept
CPS
Enter room number
204
Printing the courses: Dept: CPS; CourseNumber: 2000; Room 208
Dept: CPS; CourseNumber: 2001; Room 220
Dept: CPS; CourseNumber: 2002; Room 204
Explanation / Answer
Please find my implementation.
import java.util.Scanner;
public class Course {
private String deptCode;
private int courseNo;
private int roomNo;
private static int course = 2000;
// two constructors
public Course() {
courseNo = course;
course++;
}
public Course(String deptCode,int roomNo) {
super();
this.deptCode = deptCode;
this.courseNo = course;
course++;
this.roomNo = roomNo;
}
public String getDeptCode() {
return deptCode;
}
public int getCourseNo() {
return courseNo;
}
public int getRoomNo() {
return roomNo;
}
public void setDeptCode(String deptCode) {
this.deptCode = deptCode;
}
public void setRoomNo(int roomNo) {
this.roomNo = roomNo;
}
@Override
public String toString() {
return "Dept: "+deptCode+"; CourseNumber: "+courseNo+"; Room "+roomNo;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
for(int i=0; i<courses.length; i++) {
System.out.println("Enter Dept");
String d = sc.next();
System.out.println("Enter room number");
int r = sc.nextInt();
courses[i] = new Course(d, r);
}
sc.close();
System.out.println(" Printing the courses: ");
for(int i=0; i<courses.length; i++){
System.out.println(courses[i]);
}
}
}
/*
Sample run:
Enter Dept
CPS
Enter room number
208
Enter Dept
CPS
Enter room number
221
Enter Dept
CPS
Enter room number
204
Printing the courses:
Dept: CPS; CourseNumber: 2000; Room 208
Dept: CPS; CourseNumber: 2001; Room 221
Dept: CPS; CourseNumber: 2002; Room 204
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.