Skip to content

Commit 33a9fb8

Browse files
Solutions/generics/03 (#73)
* Update SchoolClass.java In the loop condition, pupils.size() is re-evaluated in each iteration, and because the code removed pupils from the list inside the loop, the size of the list decreases with each iteration. This is not clean and because of this an exception occurred when trying to run the function with an even amount of pupils. Furthermore the if condition to check if the size of the array is 1 needed also to be inside the loop for this solution. * Update Exercise.java Add example for even pupils * Use while loop --------- Co-authored-by: SteffenLm <33038091+SteffenLm@users.noreply.github.com>
1 parent 47571e5 commit 33a9fb8

2 files changed

Lines changed: 12 additions & 12 deletions

File tree

Exercise.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public static void main(String[] args) {
1313
schoolClass.addPupil(new Pupil("Max", "m"));
1414
schoolClass.addPupil(new Pupil("Franziska", "w"));
1515
schoolClass.addPupil(new Pupil("Jennifer", "w"));
16+
//schoolClass.addPupil(new Pupil("Jeremy", "m"));
1617

1718
schoolClass.getPairs().forEach(System.out::println);
1819
}

SchoolClass.java

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,18 @@ public void addPupil(Pupil pupil) {
1010

1111
public List<Pair<Pupil>> getPairs() {
1212
List<Pair<Pupil>> pairs = new ArrayList<>();
13-
14-
for (int i = 0; i < pupils.size(); i++) {
15-
Pupil single1 = pupils.get((new Random().nextInt(pupils.size())));
16-
pupils.remove(single1);
17-
Pupil single2 = pupils.get((new Random().nextInt(pupils.size())));
18-
pupils.remove(single2);
19-
pairs.add(new Pair<Pupil>(single1, single2));
20-
}
21-
22-
if (pupils.size() == 1) {
23-
pairs.add(new Pair<Pupil>(pupils.get(0), null));
13+
while (pupils().size() > 0) {
14+
if (pupils.size() == 1) {
15+
pairs.add(new Pair<Pupil>(pupils().get(0), null));
16+
pupils().clear();
17+
} else {
18+
Pupil single1 = pupils.get((new Random().nextInt(pupils.size())));
19+
pupils.remove(single1);
20+
Pupil single2 = pupils.get((new Random().nextInt(pupils.size())));
21+
pupils.remove(single2);
22+
pairs.add(new Pair<Pupil>(single1, single2));
23+
}
2424
}
25-
2625
return pairs;
2726
}
2827
}

0 commit comments

Comments
 (0)