Java Reference
In-Depth Information
Lines 12-14 assign new values to the elements of the total array. In line 12,
total element 0 is given the sum of denver element 0 and philadelphia element
0. Similar expressions are used in lines 13 and 14.
n
Line 15 sets the value of the average variable to the average of the three total
elements. Because average and the three total elements are integers, the average
is expressed as an integer rather than a floating-point number.
n
Lines 17-24 display the values stored in the total array and the average variable,
using the System.out.format() method to display the numeric values in a more
readable form using commas.
n
This application handles arrays in an inefficient way. The statements are almost identical,
except for the subscripts that indicate the array element to which you are referring. If the
HalfDollars application was being used to track 100 years of production totals instead
of 3 years, this approach would require a lot of redundant statements.
When dealing with arrays, you can use loops to cycle through an array's elements instead
of dealing with each element individually. This makes the code a lot shorter and easier to
read. When you learn about loops later today, you see a rewrite of the current example.
Multidimensional Arrays
If you have used arrays in other languages, you might be expecting Java to support multi-
dimensional arrays , which are arrays that contain more than one subscript and can store
information in multiple dimensions.
4
A common use of a multidimensional array is to represent the data in an x,y grid of array
elements.
Java does not support multidimensional arrays, but you can achieve the same functional-
ity by declaring an array of arrays. Those arrays can also contain arrays, and so on, for as
many dimensions as needed.
For example, consider a program that needs to accomplish the following tasks:
Record an integer value each day for a year
n
Organize those values by week
n
One way to organize this data is to create a 52-element array in which each element con-
tains a 7-element array:
int[][] dayValue = new int[52][7];
This array of arrays contains a total of 365 integers, one for each day of the year. You
could set the value for the first day of the 10th week with the following statement:
dayValue[9][0] = 14200;
Search WWH ::




Custom Search