Java Reference
In-Depth Information
The difficult work for this version of the program reduces to writing the getWords
method. This method should read all of the words from the Scanner , building up an
ArrayList<String> that contains those words and eliminating any duplicates.
Remember that our first task is to read all of the words into a list and then to sort the
list. For our purposes, we don't care about capitalization, so we can convert each
word to lowercase before we add it to the list and then, because we are using an
ArrayList<String> , we can call Collections.sort to put the list into sorted
order. Thus, we can build up the list using the following code:
while (input.hasNext()) {
String next = input.next().toLowerCase();
words.add(next);
}
Collections.sort(words);
Once the list has been sorted, duplicates of any words will be grouped together.
Remember that our plan is to build up a new list that has no duplicates. The simplest
way to eliminate duplicates is to look for transitions between words. For example, if
we have 5 occurrences of one word followed by 10 occurrences of another word, most
of the pairs of adjacent words will be equal to each other. However, in the middle of
those equal pairs, when we make the transition from the first word to the second word,
there will be a pair of words that are not equal. Whenever we see such a transition, we
know that we are seeing a new word that should be added to our new list.
Looking for transitions leads to a classic fencepost problem. For example, if there
are 10 unique words, there will be 9 transitions. We can solve the fencepost problem
by adding the first word before the loop begins. Then we can look for words that are
not equal to the words that precede them and add them to the list. Expressed as
pseudocode, our solution is as follows:
construct a new empty list.
add first word to new list.
for (each i) {
if (value at i does not equal value at i-1) {
add value at i.
}
}
This outline can be converted into actual code fairly directly, but we have to be
careful to start i at 1 rather than at 0 because in the loop we compare each word to
the one that comes before it and the first word has nothing before it. We also have to
be careful to call the ArrayList get method to obtain individual values and to use
the equals method to compare String s for equality:
ArrayList<String> result = new ArrayList<String>();
result.add(words.get(0));
 
Search WWH ::




Custom Search