Java Reference
In-Depth Information
If the word “born” is found, a boolean is set to record that it was found.
if (word.equalsIgnoreCase("born"))
foundBorn = true;
if (!foundBorn)
result = -1;
return result;
If a number and the word “born” were both found, then the number is returned. We have
found a potential birth year. If only one, or neither, are found a negative one is returned.
Finding the Correct Birth Year
Once the program finishes scanning the URLs identified with a famous person, we are
left with a list of potential birth years. The program also tracks how many times each of those
potential birth years were located. The
getResult
function is now called to determine
which year had the largest number of “votes”.
The function begins by creating two variables. The
result
variable holds the year
with the largest count. The second variable, named
maxCount
, holds the number of votes
held by the current value of the
result
variable.
int result = -1;
int maxCount = 0;
Next, a
Set
is created that contains each birth year. Each birth year is checked and at
the end, the birth year with the largest count is held in the
result
variable.
Set<Integer> set = results.keySet();
for (int year : set)
{
int count = results.get(year);
if (count > maxCount)
{
result = year;
maxCount = count;
}
}
return result;
If no birth years were found, then the result variable stays at negative one. This will indi-
cate to the calling method that no birth year was found.