Skip to content
Advertisement

Getting values from one Array List using objects of another array list java

I have 3 ArrayLists.

  1. Students (ID, Name, Program)
  2. Courses (ID, Name, Credit Hours)
  3. StudentCourses (StudentId, CourseID)

I am searching from StudentCourses by passing the StudentID and getting the courses registered with his/her name. My StudentCourse ArrayLIst has objects like this

49 (Student ID) CS233(Course ID)

49 (Student ID) CS231(Course ID)

When a user searches for a student, say I’m searching for Johnna with her registration number 49. The result is

Reg ID: 49 Name : Johnna Program: BSCS Courses Registered: CS233 CS231

Which is fine. But, what I really need to do is get the name of the course using the course IDs that appear in the search info of Johnna. The Course ArrayList looks like this:

CS233 OOP BSCS

CS231 ALgorithms BSCS

I tried this code but it didn’t seem to work. It keeps giving either garbage values or it just prints all Course names until there is a null exception:

if (myStudent == null) {
    System.out.print("No Record Was Found");
} else {
    System.out.print("Student ID: " + myStudent.getID() + "nFull Name: " + myStudent.getName() + "nProgram: " + myStudent.getProgram() +

    "nTotal Credit Hours: " + (Integer.parseInt(myStudent.getTotalCreds())) * 3420 + "Rs" + "nCourses Registered:n");
}
for (int i = 0; i < studCourseList.size(); i++) {
    if (studCourseList.get(i).getSid().equals(ID)) {

        System.out.print("- " + studCourseList.get(i).getCid() + "n");
        for (int j = 0; j < CoursesList.size(); j++) {
        if(CoursesList.get(i).getID().equals(studCourseList.get(i).getCid())){
                System.out.print("- " + CoursesList.get(i).getName() + "n");
                break;
            }

        }

    }

}

The upper portion is bringing the Student info, the first loop is for the Courses registered against the student ID, and the second loop is not working. Note that all objects are on different lines.

Advertisement

Answer

Well for starters, remove the semicolon after this if statement! if(CoursesList.get(i).getID().equals(studCourseList.get(i).getCid()))

If that doesn’t solve your problem, we’re going to need more information about what studCourseList and CoursesList is. My inclination would be to guess that in your second loop you should use j like so: if (CoursesList.get(j).getID().equals(studCourseList.get(i).getCid()))

But without explicit knowledge of your classes I can’t be sure if that is correct.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement