Java Reference
In-Depth Information
for (int i = 1; i < words.size(); i++) {
if (!words.get(i).equals(words.get(i - 1))) {
result.add(words.get(i));
}
}
There is still one minor problem with this code: If the input file is empty, there
won't be a first word to add to the new list. So, we need an extra if to make sure that
we don't try to add values to the new list if the input file is empty.
Our program now reads as follows:
1 // First version of vocabulary program that reads two files and
2 // determines the unique words in each.
3
4 import java.util.*;
5 import java.io.*;
6
7 public class Vocabulary1 {
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
16 System.out.println("list1 = " + list1);
17 System.out.println("list2 = " + list2);
18 }
19
20 public static ArrayList<String> getWords(Scanner input) {
21 // read all words and sort
22 ArrayList<String> words = new ArrayList<String>();
23 while (input.hasNext()) {
24 String next = input.next().toLowerCase();
25 words.add(next);
26 }
27 Collections.sort(words);
28
29 // add unique words to new list and return
30 ArrayList<String> result = new ArrayList<String>();
31 if (words.size() > 0) {
32 result.add(words.get(0));
Search WWH ::




Custom Search