Create a Course class with the following: A private String variable named “name”
ID: 3634206 • Letter: C
Question
Create a Course class with the following:
A private String variable named “name” to store the course’s name, such as COP3502 etc.
A private array named “students” Student[] students.
A private integer variable “capacity” for the maximum number of students allowed in this class
A private integer variable “currentEnrollment” for the number of students enrolled in the course right now
A private integer class variable named numberOfCourses that keeps track of the number of courses that have been created so far
A public constructor Course(String n, int cap)
Several set/set methods for all the properties
getName/setName
getCap/setCap
etc.
A public method enrollStudent (Student s) to add s to this course and return true if the student was successfully added, or false if not
A public method removeStudent(Student s) to remove s from the students array
Explanation / Answer
public class Course {
private static String name;
private static String[] Student=new String[10];
private static int capacity;
private static int currEnroll=0;
private int numOfCourses;
public Course()
{
}
public Course(String a,int cap)
{
name=a;
capacity=cap;
}
public void setName(String a)
{
name=a;
}
public String getName()
{
return name;
}
public void setCapacity(int cap)
{
capacity=cap;
}
public int getCapacity()
{
return capacity;
}
public static boolean enrollStudent(String name){
if(capacity>currEnroll){
Student[currEnroll]=name;
currEnroll++;
return true;
}
else
return false;
}
public static boolean removeStudent(String name){
int count=0;
for(int i=0;capacity>0 && i<capacity;i++){
if(Student[i]==name){
while(i<capacity){
Student[i]=Student[i+1];
i++;}
currEnroll--;
count=1;
}
}
if(count==1)
return true;
else
return false;
}
}
---------------------------------------------------------------------
import java.util.Scanner;
public class TestCourse {
public static void main(String[] args){
String a;
Scanner input=new Scanner(System.in);
Course c1=new Course("Ravi",5);
if(c1.enrollStudent(c1.getName())==true)
System.out.println("Student is Added Successfully");
else
System.out.println("Student Added fails");
Course c2=new Course();
System.out.println("Enter student name");
a=input.next();
c2.setName(a);
if(c2.enrollStudent(c2.getName())==true)
System.out.println("Student is Added Successfully");
else
System.out.println("Student Added fails");
if(c2.removeStudent(c2.getName())==true)
System.out.println("Student is Removed Successfully");
else
System.out.println("Student Remove fails");
}
}
--------------------------------------------------------------------------------
Output:
Student is Added Successfully
Enter student name
ammu
Student is Added Successfully
Student is Removed Successfully
BUILD SUCCESSFUL (total time: 4 seconds)