i have exercise that i Write a class CourseManager5 that stores a list of students’ objects in a given class. Each student has an id, name, score. The class allows the user to add a student, and display students’ data .. Here is the UML diagram: enter image description here The methods are:
- CourseManager5: a constructor that initializes the attributes and creates an array of students of size 100.
- getNStudents : returns the current number of students.
- addStudent: adds the student with the given object to the list. If course is full, it prints the error message: “ERROR: COURSE IS FULL” .
- displayStudent: displays all data of the student at index i.
Write a main class called TestCourseManager5 with a main method that will
do the following:
- It creates a CourseManager5 object.
- Then, it adds 3 students by reading their IDs, names, and scores from the user.
- Then, it displays all students in class.
I write the program .. but i got problem with method displayStudent .. I don't why!!
One more thing: is method addStudent correct??
Here's my program:
import java.util.Scanner;
public class TestCourseManager5 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
courseManager5 cm = new courseManager5();
int num =0;
for(int i =0; i < 3;i++){
System.out.println("Please enter the ID, name, and score of student "+num+":");
int id = s.nextInt();
String name = s.next();
double score = s.nextDouble();
student su = new student(id, name, score);
cm.addStudent(su);
num++;}
System.out.println("Student are: ");
for(int i=0;i<cm.getNStudent();i++){
cm.displayStudent(i);
}}}
public class student {
private int id;
private String name;
private double score;
public student(int id, String name, double score){
this.id = id;
this.name = name;
this.score = score;}
public int getId(){
return id;}
public String getName(){
return name;}
public double getScore(){
return score;}}
public class courseManager5 {
private student []students;
private int nStudent;
public static int MAX_SIZE = 100;
public courseManager5(){
students = new student[MAX_SIZE];
nStudent = 0;}
/addStudent adds the student with thegiven object to the list. If course is full, it prints the error message: “ERROR: COURSE IS FULL” is my method correct?/
public void addStudent (student newStudent){
if(nStudent < MAX_SIZE)
nStudent++;
else
System.out.println("ERROR: COURSE IS FULL");}
public int getNStudent(){
return nStudent;}
public void displayStudent(int i){// my problem here !
System.out.println(students[i].getId()+", "+students[i].getName()+", "+students[i].getScore());
}
}
Your problem is in addStudent(). You never added the students to the array. So, that's resulting to null in displayStudent(). Try this: