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();
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;
}names = [ghopper, null, null]names = [alovelace, null, null]Every run of the body writes toresult[0], so each username replaces the one before it. The last one stays.names = [alovelace, aturing, ghopper]Withoutindex += 1,indexis0every time, so the body only ever changesresult[0].- It doesn’t compileNothing is wrong with the program’s types, so it compiles. It just doesn’t do what the method promises.