WordPairList
has you work with an ArrayList
of WordPair
objects.
For part A you implemented a constructor that went through an array of strings. Each element of the array was paired up with each element that followed to create an ArrayList
of WordPair
references.
For example, if words
contained ["hi", "there", "bob", "smith"]
you would fill allPairs
with ["hi", "there"]
, ["hi", "bob"]
, ["hi", "smith"]
, ["there", "bob"]
, ["there", "smith"]
, ["bob", "smith"]
.
The way I solved this was with a nested loop. The first loop takes you from 0 to the end. The second starts one to the right of the first and goes to the end.
public WordPairList(String[] words) {
allPairs = new ArrayList<>();
for (int i=0; i<words.length; i++) {
for (x=i+1; x<words.length; x++) {
allPairs.add(new WordPair(words[i], words[x]));
}
}
}
In part B you needed to count how many WordPair
references in allPairs
contained the same first and second word. It’s checking that you know how to iterate through an ArrayList
, that you can get a single object out of the list, and that you know to used the equals
method instead of ==
on strings.
public int numMatches() {
int cnt = 0;
for (WordPair wp: allPairs) {
if (wp.getFirst().equals(wp.getSecond())) {
cnt++;
}
}
return cnt;
}