Create a method, getStudentId that retrieves the index in the array associated w
ID: 3888311 • Letter: C
Question
Create a method, getStudentId that retrieves the index in the array associated with the name of a student. Create a driver that will enroll 5 students. Call the getStudentId to retrieve the ID for one of the 5 enrolled students. (JAVA)
existing code:
public class GradeBook{
private enum EnrollmentStatus {OPEN, FULL};
private EnrollmentStatus enrollment;
private int occupiedSlots;
private int maxSlots;
private String[] names;
public GradeBook(int maxSlots){
this.occupiedSlots = 0;
this.maxSlots = maxSlots;
enrollment = EnrollmentStatus.OPEN;
names = new String [maxSlots];
}
public int getMaxSlots(){
return maxSlots;
}
public int getAvailbleSlots(){
return maxSlots - occupiedSlots;
}
public boolean enroll(String name){
if(enrollment == EnrollmentStatus.FULL)
return false;
else {
names[occupiedSlots++] = name;
if(occupiedSlots>=maxSlots)
enrollment = EnrollmentStatus.FULL;
}
return true;
}
}
Explanation / Answer
Below is your code. I am assuming here that IDs start from 0.
public class GradeBook {
private enum EnrollmentStatus {
OPEN, FULL
};
private EnrollmentStatus enrollment;
private int occupiedSlots;
private int maxSlots;
private String[] names;
public GradeBook(int maxSlots) {
this.occupiedSlots = 0;
this.maxSlots = maxSlots;
enrollment = EnrollmentStatus.OPEN;
names = new String[maxSlots];
}
public int getMaxSlots() {
return maxSlots;
}
public int getAvailbleSlots() {
return maxSlots - occupiedSlots;
}
public boolean enroll(String name) {
if (enrollment == EnrollmentStatus.FULL)
return false;
else {
names[occupiedSlots++] = name;
if (occupiedSlots >= maxSlots)
enrollment = EnrollmentStatus.FULL;
}
return true;
}
// Assuming IDs start from 0, returning -1 if not found
public int getStudentId(String nme) {
for (int i = 0; i < names.length; i++) {
if (names[i] == nme) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
GradeBook gb = new GradeBook(5);
gb.enroll("Sanjay");
gb.enroll("Shivy");
gb.enroll("Deepak");
gb.enroll("Vijay");
gb.enroll("Sunil");
int id = gb.getStudentId("Deepak");
if (id == -1) {
System.out.println("Student not enrolled");
} else{
System.out.println("Student id of Deepak is : " + id);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.