Page 418 - Introduction to Programming with Java: A Problem Solving Approach
P. 418
384 Chapter 10 Arrays and ArrayLists
/********************************************************************
*
MovingAverage.java
Dean & Dean
This program contains an operation that shifts each array
element to the next lower element and loads a new input
into the final element.
********************************************************************/
*
*
*
*
*
import java.util.Scanner;
public class MovingAverage
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
int[] days = {9400, 9500, 9600, 9700}; // rising market
double sum;
int samples;
System.out.print("Enter number of days to evaluate: ");
samples = stdIn.nextInt();
for (int j=0; j<samples; j++)
{
Apago PDF Enhancer
// shift down and sum
sum = 0.0;
for (int d=0; d<days.length-1; d++)
{
}
// end class MovingAverage
}
// end main
}
days[d] = days[d+1];
sum += days[d];
}
System.out.print("Enter next day's value: ");
days[days.length-1] = stdIn.nextInt();
sum += days[days.length-1];
System.out.printf(
"Moving average = %5.0f\n", sum / days.length);
This shifts to lower- index positions.
This accumulates the already-shifted values.
This shifts in the latest value.
Figure 10.7 Calculation of a moving average
Conceptually, the arraycopy method copies everything from element 1 to the last element into a tempo- rary array, and then copies it from this temporary array back into the original array starting at element 0. This eliminates the inner for loop in Figure 10.7. Unfortunately, we also used the inner for loop to compute the sum needed for the average. But there’s a trick you can use, and it makes a program like this more efficient when the array is very large. If you keep track of the sum of all the elements in the array, each time you shift the array element values, you can just correct the sum, rather than completely re-computing it. To correct the sum, subtract the value shifted out and add the value shifted in, like this: