您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 4

Motivation for using arrays

Here is an example of the use of an array. Suppose a program performs calculations on sales totals recorded each month. To store the monthly totals we could define a variable for each month like this: 

double januarySales;
double februarySales;
//...
double decemberSales;
All the monthly totals can be added together to give an annual total like this: 
double annualSales = januarySales + februarySales + marchSales + aprilSales
        + /* other months */ + decemberSales;
While this strategy is just about viable when there are twelve variables, what would happen with, say, 2,000 variables? The program would be extremely long and ugly, and it would be easy to make a mistake and refer to the wrong variable. 

An alternative approach is to define an array to store the monthly totals. There are twelve months in the year, so we need an array with 12 elements. In Java: 

double monthlySales[] = new double[12]; 
This can be read as "The variable monthlySales is an array of doubles. Make it a new array of doubles with 12 elements". 

Then instead of writing 

januarySales = 1234;
februarySales = 2345;
//... etc
We would write 
monthlySales[0] = 1234;
monthlySales[1] = 2345;
// ... etc
We have assumed here that January is month number 0, February is number 1, and so on, up to December which is number 11. This brings out an extremely important point: array elements in Java are always numbered from 0, not from 1. This means that if an array has 100 elements, the last element is numbered 99, not 100, as the first is 0, not 1. 

This very often causes confusion for novice programmers; if your Java program reports errors like "arrayBoundsException" then this mistake is very likely to be the cause. 

So how do we add the monthly totals to give an annual total now? Here is the Java: 

double annualTotal = 0;
for(int i = 0; i < 12; i++)
        annualTotal = annualTotal + monthlySales[i];
In this example we aere using a variable to refer to the appropriate array element, that is, rather than something like :
monthlySales[0]
we am writing:
monthlySales[i]
This means that if i has the value 3, we are then referring to the monthlySales values for April. In general, as the value of i changes, we can look at the monthly sales figures for that month (the i'th month). This ability to use a variable to select a particular array element is an extremely powerful feature, and is found in almost all programming languages. 

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg