I’m working on my first programming assignment for Java and I had another question. I put a Course[] inside of Student[] but now seem to be encountering a NullPointerException error and I can’t figure out why.
public Student[] analyzeData() {
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream("Programming Assignment 1 Data.txt"));
} catch (FileNotFoundException e) {
System.out.println("File Programming Assignment 1 Data.txt could not be found or opened.");
System.exit(0);
}
int numberOfStudents = inputStream.nextInt();
int tuitionPerHour = inputStream.nextInt();
Student[] students = new Student[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
String firstName = inputStream.next();
String lastName = inputStream.next();
int studentID = inputStream.nextInt();
String isTuitionPaid = inputStream.next();
int numberOfCourses = inputStream.nextInt();
Course[] courses = new Course[numberOfCourses];
for (i = 0; i < numberOfCourses; i++) {
String courseName = inputStream.next();
String courseNumber = inputStream.next();
int creditHours = inputStream.nextInt();
String grade = inputStream.next();
Course currentCourse = new Course(courseName, courseNumber, creditHours, grade);
courses[i] = currentCourse;
}
Student currentStudent = new Student(firstName, lastName, studentID, isTuitionPaid, numberOfCourses, courses);
students[i] = currentStudent;
}
return students;
}
The formatting for the input file is:
3 345
Lisa Miller 890238 Y 2
Mathematics MTH345 4 A
Physics PHY357 3 B
Bill Wilton 798324 N 2
English ENG378 3 B
Philosophy PHL534 3 A
Where courses has information about the courses, and students has information about the students.
I would add an array (or better yet, ArrayList or a Map) to
Studentthat contains the classes the student is taking.With what you’re doing, how are you determining which classes go with which students?
Try adding the following instance variable
to
Student, then implement the following methods to add to the List or return the whole thing.And reading files can be a real pain, what you have is ok, at least for now. Your loop where
Courseis instantiated would include a callstudent.addCourse(course). Then you’ll be golden.Be advised this is a high level overview so there could be some learnage in here for you. Just post back and we’ll help.