Mohammed Alhashim
Mohammed Alhashim

Reputation: 13

How to link two arrays together

I have just started taking java course at the university and I would like to link two arrays.

I have created a 1D arrays called, StudentID[] this will store the student ID.

I have created another 2D array called SubjTaken[] [] which will contain subject, credit hour, grade letter.

Now, I want to link those two arrays. For example,

Inpute would be:

ENTER STUDENT ID:

123456

ENTER SUBJECTS TAKEN:

MATH101 4 A

PHYS201 3 B+

Then it will store them in both arrays. And will be able to call it later. For example:

ENTER STUDENT ID:

123456

THE SUBJECT THAT YOU TOOK ARE:

MATH101 4 A

PHYS201 3 B+

My problem is: I dont know how to create a link with them. If I have 5 students I will need to have 5 2d arrays and I will need to link each one of them. I thought about array inside an array. Looking for help.

Upvotes: 0

Views: 3407

Answers (3)

npinti
npinti

Reputation: 52185

Linking arrays the way you are suggesting is not ideal since you will end up with 3 Dimensional arrays which tend to make life a little bit more complicated. What you can do, however, is to use a data structure such as a HashMap. Hashmaps allow you to store data in a key-value pair combination, so in your case, you can have a Hashmap that has student ID's as its key and the respective value would be the corrisponding 2d array. So you can have something like this:

HashMap<String, String[][]> studentData = new HashMap<String, String[][]>();
//Add some data to it
studentData.put(studentID, subjTaken);

You can check the API link I have provided to see what you can do. To print all the data in the HashMap, you can, for instance, dome something like this:

for (String id : studentData.keySet())
{
    System.out.println("Student ID: " + id");
    String[][] subjects = studentData.get(id);
    for(String str :subjects)
    {
         System.out.println("Subject: " + str);
    }
}

Just as an extra note, the solution provided by Isaac Truett is more elegant and more suitable. The solution I have provided on the other hand, allows you to study data structures other than arrays.

Upvotes: 0

kuriouscoder
kuriouscoder

Reputation: 5582

I agree with Isaac Truett.

To elaborate further you could do the following:


import java.util.list;
public class Student {
    String id;
    List<SubjectReport> progressReport;
}

public class SubjectReport {
    Subject subject;
    Grade grade;
}

public class Subject {
   String courseName;
   int courseNumber;
}

public enum Grade {
    A;
    A-;
    B+;
    B;
    B-;
    F;
}

Upvotes: 2

Isaac Truett
Isaac Truett

Reputation: 8884

Rather than fiddle around with arrays, just create a Student class that has a List of Subjects.

Upvotes: 7

Related Questions