☰ Contents Collecting Values

Collecting Values in Summary

Each of these CourseRoster methods loops over students. Which kind of loop fits each one best?
String[] usernames() – every student’s username, in order:
int countWithShortNames(int max) – how many students have a displayName shorter than max:
Student longestName() – the student whose displayName is longest:
String allIds() – every id, joined into one String:
Write the body of usernames, which returns a new array with each student’s username, in order.
record Student(String displayName, String username, String id) { }
record CourseRoster(Student[] students) {
String[] usernames() {

}
}
Student ada = new Student("Ada Lovelace", "alovelace", "A10000001");
Student alan = new Student("Alan Turing", "aturing", "A10000002");
Student grace = new Student("Grace Hopper", "ghopper", "A10000003");
Student[] enrolled = { ada, alan, grace };
CourseRoster cse11 = new CourseRoster(enrolled);
String[] names = cse11.usernames();

Here is usernames with one line left out. With the same cse11 as above, what does the book show for names?

String[] usernames() {
  String[] result = new String[students.length];
  int index = 0;
  for(Student s: students) {
    result[index] = s.username;
  }
  return result;
}
  1. names = [ghopper, null, null]
  2. names = [alovelace, null, null]
    Every run of the body writes to result[0], so each username replaces the one before it. The last one stays.
  3. names = [alovelace, aturing, ghopper]
    Without index += 1, index is 0 every time, so the body only ever changes result[0].
  4. It doesn’t compile
    Nothing is wrong with the program’s types, so it compiles. It just doesn’t do what the method promises.