Java Reference
In-Depth Information
we want to continue in the
while
loop as long as the two index variables haven't
reached the end of the list. We also have to figure out how to compare the two words.
Because the
String
class implements the
Comparable
interface, we can use its
compareTo
method. Finally, we have to construct an
ArrayList
to store the overlap,
and we have to return this list after the loop has completed executing.
Thus, we can turn our pseudocode into the following actual code:
ArrayList<String> result = new ArrayList<String>();
int i1 = 0;
int i2 = 0;
while (i1 < list1.size() && i2 < list2.size()) {
int num = list1.get(i1).compareTo(list2.get(i2));
if (num == 0) {
result.add(list1.get(i1));
i1++;
i2++;
} else if (num < 0) {
i1++;
} else { // num > 0
i2++;
}
}
return result;
After we turn this code into a method and modify
main
to call the method and to
report the overlap, we end up with the following new version of the program:
1 // Second version of vocabulary program which reads two files
2 // and reports the overlap between them.
3
4
import
java.util.*;
5
import
java.io.*;
6
7
public class
Vocabulary2 {
8
public static void
main(String[] args)
9
throws
FileNotFoundException {
10 Scanner in1 =
new
Scanner(
new
File("test1.txt"));
11 Scanner in2 =
new
Scanner(
new
File("test2.txt"));
12
13 ArrayList<String> list1 = getWords(in1);
14 ArrayList<String> list2 = getWords(in2);
15 ArrayList<String> common = getOverlap(list1, list2);
16
17 System.out.println("list1 = " + list1);
18 System.out.println("list2 = " + list2);
Search WWH ::
Custom Search