The Running-Value Pattern
Summing, counting, and finding the slowest page load are the same loop, walked once — and it's the pattern that fixes the average bug from Chapter 4.
Here is the correct answer to a bug you already met. In Chapter 4, Bug Hunt #4
reported an average of 98 ms that should have been 128. This computes it properly,
casting one side to double so the fraction survives, exactly as Chapter 2 taught:
public class Arr2 {
public static void main(String[] args) {
int[] responseTimes = {120, 95, 210, 88};
int total = 0;
for (int i = 0; i < responseTimes.length; i++) {
total += responseTimes[i];
}
double average = (double) total / responseTimes.length;
System.out.println("Total : " + total);
System.out.println("Average: " + average + " ms");
}
}
Total : 513
Average: 128.25 ms
The same shape, three jobs
The pattern of walking an array while carrying a running value is one you will use constantly. Sum, count, and "find the largest" are all the same shape. Here is the largest:
public class Arr3 {
public static void main(String[] args) {
int[] loadTimes = {340, 180, 520, 260, 410};
int slowest = loadTimes[0];
for (int i = 1; i < loadTimes.length; i++) {
if (loadTimes[i] > slowest) {
slowest = loadTimes[i];
}
}
System.out.println("Slowest page load: " + slowest + " ms");
}
}
Slowest page load: 520 ms
Start by assuming the first item is the answer, then walk the rest and keep a better
one whenever you find it. Notice the loop starts at i = 1, because position 0 is
already your starting guess — a deliberate, correct use of starting at one, very
different from the silent off-by-one bug of the last chapter, which skipped real data
by accident.
Every running-value loop you write follows this same shape: start with a value that
makes sense before you've seen anything (0 for a sum, the first item for a max),
then walk the rest, updating as you go. Once you can see that shape, sum, count, and
max stop being three things to memorize and become one thing to recognize.