___________________ ___________________ ___________________
import java.io.*;
import java.util.*;
public class SimpleWordCount {
public static void main(String[] args) throws FileNotFoundException
{
Scanner s = new Scanner(new File("test.txt"));
String text = s.useDelimiter("\\Z").next();
String[] words = text.split("\\s+");
Arrays.sort(words);
String lastUnique = words[0];
int count = 1;
for (int k = 1; k < words.length; k=k+1)
{
String current = words[k];
if (current.equals(lastUnique))
{ // same as previous one
count = count + 1;
}
else
{ // new word
System.out.println(lastUnique + "\t"+ count);
lastUnique = current;
count = 1;
}
}
System.out.println(lastUnique + "\t"+ count);
}
}
Questions? What does this code do?
On December 31, 2008, some models of the Zune, Microsoft's portable music player, went dark. The devices were unusable until the following day. Failures like this are sometimes caused by complex chains of mishaps, but this particular one is due to a single programming error that is reasonably easy to understand. Let's take a look.
Here is the offending code (reformatted slightly), in the part of the Zune's software that handles dates and times:
year = 1980;
while (days > 365) {
if (IsLeapYear(year)) {
if (days > 366) {
days -= 366;
year += 1;
}
} else {
days -= 365;
year += 1;
}
}
At the beginning of this code, the variable days is the number of days that have elapsed since January 1, 1980. Given this information, the code is supposed to figure out (a) what year it is, and (b) how many days have elapsed since January 1 of the current year. (Footnote for pedants: here "elapsed since" actually means "elapsed including", so that days=1 on January 1, 1980.)