Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

6.2 Data sets — parallel arrays and filtering

Lesson

Records in parallel arrays

Real data sets have records with several fields. One simple way to store them is parallel arrays: two arrays of the same length where the same index refers to the same record. Here names[i] and scores[i] belong to the same student. To match them up you must loop with an index i — a for-each loop only hands you values, not the index needed to line up the two arrays.


Worked example

Filtering keeps only the records that meet a condition. Without knowing how many will match, count first, then fill a result array of that exact size:

String[] names = {"Ada", "Sam", "Kai", "Mia"};
int[] scores = {55, 88, 91, 60};
int count = 0;
for (int i = 0; i < scores.length; i++) {   // pass 1: how many pass?
    if (scores[i] >= 60) {
        count++;
    }
}
String[] passers = new String[count];
int j = 0;
for (int i = 0; i < scores.length; i++) {   // pass 2: collect names
    if (scores[i] >= 60) {
        passers[j] = names[i];
        j++;
    }
}

Passing students (score at least 60) are Sam, Kai, and Mia, so passers is {Sam, Kai, Mia}. (An ArrayList from java.util is the other common way to collect matches without two passes.)


▶ Try it: run this, then change the threshold or the records and re-run to see who passes.



In parallel arrays, names[i] and scores[i]...


To line up two parallel arrays, you must loop with...


Type exactly what this program prints.

String[] names = {"Bo", "Cy", "Di"};
int[] scores = {40, 80, 95};
for (int i = 0; i < scores.length; i++) {
    if (scores[i] >= 70) {
        System.out.println(names[i]);
    }
}

Why can't a for-each loop line up two parallel arrays?


True or false?