Tải bản đầy đủ (.pdf) (473 trang)

Ebook Java: An introduction to problem solving & programming (Sixth edition) – Part 2

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.27 MB, 473 trang )

Arrays

7.4 SORTING AND SEARCHING ARRAYS 525
Selection Sort 525
Other Sorting Algorithms 529
Searching an Array 531

7.1 ARRAY BASICS 481
Creating and Accessing Arrays 482
Array Details 485
The Instance Variable length 488
More About Array Indices 491
Initializing Arrays 494

7.5 MULTIDIMENSIONAL ARRAYS 532
Multidimensional-Array Basics 533
Multidimensional-Array Parameters and Returned
Values 536
Java’s Representation of Multidimensional
Arrays 539
Ragged Arrays (Optional ) 540
Programming Example: Employee Time
Records 542

7.2 ARRAYS IN CLASSES
AND METHODS 495
Case Study: Sales Report 495
Indexed Variables as Method Arguments 503
Entire Arrays as Arguments to a Method 505
Arguments for the Method main 507
Array Assignment and Equality 508


Methods That Return Arrays 511
7.3 PROGRAMMING WITH ARRAYS
AND CLASSES 515
Programming Example: A Specialized List Class
Partially Filled Arrays 523

Chapter Summary

556

7

515

Programming Projects

7.6 GRAPHICS SUPPLEMENT 548
Text Areas and Text Fields 548
Programming Example: A Question-and-Answer
Applet 548
The Classes JTextArea and JTextField 551
Drawing Polygons 553

562

Answers to Self-Test Questions

568



They stood at attention in a neat row, all with the same uniform, yet each
with his own values.
‰8"33&/1&"$&
The Lieutenant’s Array

An array is a special kind of object used to store a collection of data. An array
differs from the other objects you have seen in two ways:
t "MM UIF EBUB TUPSFE JO BO BSSBZ NVTU CF PG UIF TBNF UZQF 'PS FYBNQMF

you might use an array to store a list of values of type double that record
rainfall readings in centimeters. Or you might use an array to store a list
of objects of some class called Species that contain the records for various
endangered species.
t "OBSSBZPCKFDUIBTPOMZBTNBMMOVNCFSPGQSFEFGJOFENFUIPET#FDBVTF
arrays were used by programmers for many years before classes were
JOWFOUFE
 UIFZ VTF B TQFDJBM OPUBUJPO PG UIFJS PXO UP JOWPLF UIPTF GFX
QSFEFGJOFE NFUIPET
 BOE NPTU QFPQMF EP OPU FWFO UIJOL PG UIFN BT
methods.
*OUIJTDIBQUFS
XFJOUSPEVDFZPVUPBSSBZTBOETIPXZPVIPXUPVTFUIFN
in Java.

OBJECTIVES
"GUFSTUVEZJOHUIJTDIBQUFS
ZPVTIPVMECFBCMFUP
t %FTDSJCFUIFOBUVSFBOEQVSQPTFPGBOBSSBZ
t 6TFBSSBZTJOTJNQMF+BWBQSPHSBNT
t %FGJOFNFUIPETUIBUIBWFBOBSSBZBTBQBSBNFUFS

t %FGJOFNFUIPETUIBUSFUVSOBOBSSBZ
t 6TFBOBSSBZBTBOJOTUBODFWBSJBCMFJOBDMBTT
t 6TFBOBSSBZUIBUJTOPUGJMMFEDPNQMFUFMZ
t 0SEFS
PSTPSU
UIFFMFNFOUTJOBOBSSBZ
t 4FBSDIBOBSSBZGPSBQBSUJDVMBSJUFN
t %FGJOFBOEVTFNVMUJEJNFOTJPOBMBSSBZT
t *OTFSUUFYUGJFMETBOEUFYUBSFBTJOUPZPVSBQQMFUT
t %SBXBSCJUSBSZQPMZHPOTJOZPVSBQQMFUT

PREREQUISITES
This is the first point in this book where you have a significant choice as to
XIBUUPSFBEOFYU*GZPVQSFGFS
JOTUFBEPGSFBEJOHUIJTDIBQUFSOPX
ZPVDBO
go on in the book and return to this discussion of arrays at a later time. You
480


7.1 Array Basics

481

DBOSFBE$IBQUFSTUISPVHI


BOE
FYDFQUGPS4FDUJPO
BT

ZPVXJTICFGPSFZPVSFBEUIJTDIBQUFS4FDUJPOTBOEJODMVEFSFGFSFODFT
UPBSSBZTGPSTPNFPGUIFFYBNQMFT
4FDUJPOEFQFOETPOMZPO$IBQUFSTUISPVHI)PXFWFS
ZPVTIPVME
be familiar with the material in all of the previous chapters before reading the
remaining sections of this chapter.
*G ZPV BSF SFBEJOH UIF HSBQIJDT TVQQMFNFOU TFDUJPOT JO FBDI DIBQUFS

you can—and are encouraged to—read the first part of this chapter’s graphic
TVQQMFNFOU
XIFUIFSZPVSFBEUIFSFTUPGUIFDIBQUFSPSOPU

7.1 ARRAY BASICS
And in such indexes, although small pricks
To their subsequent volumes, there is seen
The baby figure of the giant mass
Of things to come.
—WILLIAM SHAKESPEARE, TROILUS AND CRESSIDA

4VQQPTFZPVXBOUUPDPNQVUFUIFBWFSBHFUFNQFSBUVSFGPSUIFTFWFOEBZTJOB
week. You might use the following code:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 7 temperatures:");
double sum = 0;
for (int count = 0; count < 7; count++)
{
double next = keyboard.nextDouble();
sum = sum + next;
}
double average = sum / 7;


5IJTXPSLTGJOFJGBMMZPVXBOUUPLOPXJTUIFBWFSBHF#VUMFUTTBZZPVBMTP
want to know which temperatures are above and which are below the average.
/PX ZPV IBWF B QSPCMFN *O PSEFS UP DPNQVUF UIF BWFSBHF
 ZPV NVTU SFBE
UIFTFWFOUFNQFSBUVSFT
BOEZPVNVTUDPNQVUFUIFBWFSBHFCFGPSFDPNQBSJOH
FBDIUFNQFSBUVSFUPJU5IVT
UPCFBCMFUPDPNQBSFFBDIUFNQFSBUVSFUPUIF
BWFSBHF
ZPVNVTUSFNFNCFSUIFTFWFOUFNQFSBUVSFT)PXDBOZPVEPUIJT 
The obvious answer is to use seven variables of type double. This is a bit
BXLXBSE
CFDBVTFTFWFOJTBMPUPGWBSJBCMFTUPEFDMBSF
BOEJOPUIFSTJUVBUJPOT

the problem can be even worse. Imagine doing the same thing for each day of
UIFZFBSJOTUFBEPGKVTUFBDIEBZPGUIFXFFL8SJUJOHWBSJBCMFEFDMBSBUJPOT
would be absurd. Arrays provide us with an elegant way to declare a collection
of related variables. An array is a collection of items of the same type. It is Items in an array
TPNFUIJOHMJLFBMJTUPGWBSJBCMFT
CVUJUIBOEMFTUIFOBNJOHPGUIFWBSJBCMFTJO have the same
data type
BOJDF
DPNQBDUXBZ


482

CHAPTER 7 / Arrays


Creating and Accessing Arrays
*O+BWB
BOBSSBZJTBTQFDJBMLJOEPGPCKFDU
CVUJUJTPGUFONPSFVTFGVMUPUIJOLPGBO
BSSBZBTBDPMMFDUJPOPGWBSJBCMFTPGUIFTBNFUZQF'PSFYBNQMF
BOBSSBZDPOTJTUJOH
of a collection of seven variables of type double can be created as follows:
double[] temperature = new double[7];

This is like declaring the following seven strangely named variables to have
the type double:
temperature[0], temperature[1], temperature[2], temperature[3],
temperature[4], temperature[5], temperature[6]
An index is
an integer
expression that
indicates an array
element

Variables like temperature[0] and temperature[1] that have an integer
FYQSFTTJPO JO TRVBSF CSBDLFUT BSF DBMMFE indexed variables, subscripted
variable, array elements, or simply elements.5IFJOUFHFSFYQSFTTJPOXJUIJO
UIFTRVBSFCSBDLFUTJTDBMMFEBOindex or a subscript. Note that the numbering
TUBSUTXJUI
OPU

REMEMBER Array Indices Begin at 0
In Java, the indices of an array always start with 0. They never start with 1
or any number other than 0.


Each of these seven variables can be used just like any other variable of
type double'PSFYBNQMF
BMMPGUIFGPMMPXJOHTUBUFNFOUTBSFBMMPXFEJO+BWB
temperature[3] = 32;
temperature[6] = temperature[3] + 5;
System.out.println(temperature[6]);

8IFOXFUIJOLPGUIFTFJOEFYFEWBSJBCMFTBTCFJOHHSPVQFEUPHFUIFSJOUPPOF
DPMMFDUJWFJUFN
XFXJMMDBMMUIFNBOBSSBZ4PXFDBOSFGFSUPUIFBSSBZOBNFE
temperatureXJUIPVUVTJOHBOZTRVBSFCSBDLFUT'JHVSFJMMVTUSBUFTUIFBSSBZ
temperature.
#VUUIFTFTFWFOWBSJBCMFTBSFNPSFUIBOKVTUTFWFOQMBJOPMEWBSJBCMFTPG
type double 5IF OVNCFS JO TRVBSF CSBDLFUT JT QBSU PG UIF OBNF PG FBDI PG
UIFTFWBSJBCMFT
BOEJUEPFTOPUIBWFUPCFBOJOUFHFSDPOTUBOU*OTUFBE
ZPV
DBOVTFBOZFYQSFTTJPOUIBUFWBMVBUFTUPBOJOUFHFSUIBUJTBUMFBTUBOE‰GPS
UIJTFYBNQMF‰BUNPTU4PUIFGPMMPXJOHDPEF
GPSJOTUBODF
JTBMMPXFE
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter day number (0 - 6):");
int index = keyboard.nextInt();
System.out.println("Enter temperature for day " + index);
temperature[index] = keyboard.nextDouble();


7.1 Array Basics


FIGURE 7.1 A Common Way to Visualize an Array
Indices
0

1

2

3

4

5

6

32

30

25.7

26

34

31.5

29


The array temperature
temperature[5]

4JODFBOJOEFYDBOCFBOFYQSFTTJPO
XFDBOXSJUFBMPPQUPSFBEWBMVFTJOUP
the array temperature
BTGPMMPXT
System.out.println("Enter 7 temperatures:");
for (int index = 0;index < 7; index++)
temperature[index] = keyboard.nextDouble();

5IFVTFSDPVMEUZQFUIFTFWFOWBMVFTPOTFQBSBUFMJOFTPSBMMPOPOFMJOF
TFQBSBUFE
CZTQBDFT"GUFSUIFBSSBZWBMVFTBSFSFBEJO
XFDBOEJTQMBZUIFNBTGPMMPXT
System.out.println("The 7 temperatures are:");
for (int index = 0; index < 7; index++)
System.out.print(temperature[index] + " ");
System.out.println( );

5IFQSPHSBNJO-JTUJOHTIPXTBOFYBNQMFUIBUVTFTPVSTBNQMFBSSBZ
temperature BT TFWFO JOEFYFE WBSJBCMFT
 BMM PG UZQF double. Note that the
program uses for loops similar to the ones we just considered.

LISTING 7.1

An Array of Temperatures (part 1 of 2)


/**
Reads 7 temperatures from the user and shows which are above
and which are below the average of the 7 temperatures.
*/
import java.util.Scanner;
public class ArrayOfTemperatures
{
public static void main(String[] args)
{
double[] temperature = new double[7];
// Read temperatures and compute their average:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 7 temperatures:");
double sum = 0;
for (int index = 0; index < 7; index++)

(continued)

483


484

CHAPTER 7 / Arrays

LISTING 7.1 An Array of Temperatures (part 2 of 2)
{
temperature[index] = keyboard.nextDouble();
sum = sum + temperature[index];
}

double average = sum / 7;
System.out.println("The average temperature is " +
average);
// Display each temperature and its relation to the average:
System.out.println("The temperatures are");
for (int index = 0; index < 7; index++)
{
if (temperature[index] < average)
System.out.println(temperature[index] +
" below average");
else if (temperature[index] > average)
System.out.println(temperature[index] +
" above average");
else //temperature[index] == average
System.out.println(temperature[index] +
" the average");
}
System.out.println("Have a nice week.");
}
}

Sample Screen Output
Enter 7 temperatures:
32
30
25.7
26
34
31.5
29

The average temperature is 29.7428
The temperatures are
32.0 above average
30.0 above average
25.7 below average
26.0 below average
34.0 above average
31.5 above average
29.0 below average
Have a nice week.


7.1 Array Basics

485

Array Details
You create an array in the same way that you would create an object of a class
type using the operation new
 CVU UIF OPUBUJPO JT TMJHIUMZ EJGGFSFOU 8IFO
creating an array of elements of type Base_Type
UIFTZOUBYJTBTGPMMPXT
Base_Type[] Array_Name = new Base_Type[Length];

'PSFYBNQMF
UIFGPMMPXJOHDSFBUFTBOBSSBZOBNFEpressureUIBUJTFRVJWBMFOU
UPWBSJBCMFTPGUZQFint:
int[] pressure = new int[100];

"MUFSOBUJWFMZ

UIFQSFDFEJOHDBOCFCSPLFOEPXOJOUPUXPTUFQT
int[] pressure;
pressure = new int[100];

The first step declares as an
array of integers. The second
ASIDE Alternative Syntax for Declaring
step allocates enough memory
an Array
GPSUIFBSSBZUPIPMEVQUP
Although we do not encourage its use, there
integers.
is an alternative syntax for array declarations
The type for the array
that you may encounter. You can write the
square brackets after the variable instead
elements is called the base
of after the base type, as in the following
type of the array. In this
example:
FYBNQMF
UIFCBTFUZQFJT int.
The number of elements in
char alphabet[];
an array is called the length,
size, or capacity of the array.
4P UIJT TBNQMF BSSBZ pressure IBT MFOHUI 
 XIJDI NFBOT JU IBT JOEFYFE
variables pressure[0]through pressure[99]. Note that because the indices
TUBSU BU 

 BO BSSBZ PG MFOHUI 
 TVDI BT pressure
 XJMM IBWF no JOEFYFE
variable pressure[100].
5IF CBTF UZQF PG BO BSSBZ DBO CF BOZ EBUB UZQF *O QBSUJDVMBS
 JU DBO CF
a class type. The following statement creates an array named entry whose
elements are SpeciesPCKFDUT
XIFSFSpecies is a class:
Species[] entry = new Species[3];

This array is a collection of the three variables entry[0]
 entry[1]
 BOE
entry[2]
BMMPGUZQFSpecies.

RECAP Declaring and Creating an Array
You declare and create an array in almost the same way that you declare
and create objects of classes. There is only a slight difference in the
syntax.
(continued)

The number of
elements in an
array is its length

The type of the
array elements is
the array’s base

type


486

CHAPTER 7 / Arrays

SYNTAX
Base_Type[] Array_Name

= new Base_Type[Length];

EXAMPLES
char[] symbol = new char[80];
double[] reading = new double[100];
Species[] specimen = new Species[80]; //Species is a class

REMEMBER How to Use Square Brackets with Arrays
There are three different ways to use square brackets [] with an array
name. They can be used
t 8JUIBEBUBUZQFXIFOEFDMBSJOHBOBSSBZ'PSFYBNQMF
int[] pressure;

declares—but does not allocate memory for—pressure as an array of inteHFST
t 5PFODMPTFBOJOUFHFSFYQSFTTJPOXIFODSFBUJOHBOFXBSSBZ'PSFYBNQMF
pressure = new int[100];

allocates memory for the array pressurePGJOUFHFST
t 5POBNFBOJOEFYFEWBSJBCMFPGUIFBSSBZ'PSFYBNQMF
pressure[3] in the

following two lines is an indexed variable:
pressure[3] = keyboard.nextInt();
System.out.println("You entered" + pressure[3]);

"TXFNFOUJPOFEQSFWJPVTMZ
UIFWBMVFJOTJEFUIFTRVBSFCSBDLFUTDBOCF
BOZ FYQSFTTJPO UIBU FWBMVBUFT UP BO JOUFHFS 8IFO DSFBUJOH BO BSSBZ
 JOTUFBE
PGVTJOHBOJOUFHFSMJUFSBM
ZPVDBO‰BOETIPVME‰VTFBOBNFEDPOTUBOU'PS
FYBNQMF
ZPVTIPVMEVTFBDPOTUBOUTVDIBT NUMBER_OF_READINGS instead of
XIFOZPVDSFBUFUIFBSSBZpressure:
Use a named
constant when
defining an array

public static final int NUMBER_OF_READINGS = 100;
int[] pressure = new int[NUMBER_OF_READINGS];

+BWB BMMPDBUFT NFNPSZ GPS BO BSSBZ
 BT XFMM BT GPS BOZ PUIFS PCKFDU
 BU
FYFDVUJPO UJNF 4P JG ZPV EP OPU LOPX IPX MBSHF UP NBLF BO BSSBZ XIFO
ZPVXSJUFBQSPHSBN
ZPVDBOSFBEUIFBSSBZTMFOHUIGSPNUIFLFZCPBSE
BT
follows:



7.1 Array Basics

487

FIGURE 7.2 Array Terminology
Array name
temperature[n + 2]

Index (also called a subscript)
Indexed variable (also
called an array element, an
element, or a subscripted
variable)

temperature[n + 2]

temperature[n + 2]

Value of the indexed
variable (also called an
element of the array)

temperature[n + 2] = 32;

System.out.println("How many temperatures do you have?");
int size = keyboard.nextInt();
double[] temperature = new double[size];

:PVDBOBMTPVTFBOZFYQSFTTJPOUIBUFWBMVBUFTUPBOBQQSPQSJBUFJOUFHFS
XIFOOBNJOHBOJOEFYFEWBSJBCMFPGBOBSSBZ

BTJOUIFGPMMPXJOHFYBNQMFT
int point = 2;
temperature[point + 3] = 32;
System.out.println("Temperature is " + temperature[point + 3]);

Note that temperature[point + 3]JOUIFQSFDFEJOHDPEFJTUIFTBNFJOEFYFE
variable as temperature[5]
CFDBVTFpoint + 3FWBMVBUFTUP
'JHVSFJMMVTUSBUFTTPNFPGUIFNPTUDPNNPOUFSNTVTFEXIFOSFGFSSJOH
to arrays. Notice that the word element has two meanings. It can be used to
SFGFSUPBOJOEFYFEWBSJBCMFBTXFMMBTUPUIFWBMVFPGBOJOEFYFEWBSJBCMF

■ PROGRAMMING TIP

In General, Use Singular Names for
Arrays

*GZPVXBOUBOBSSBZUPIPMEFOUSJFT
FBDIPGXIJDIJTBOPCKFDUPGBDMBTTDBMMFE
Species
ZPVNJHIUCFUFNQUFEUPVTFTPNFUIJOHMJLFUIFGPMMPXJOH
Species[] entries = new Species[20]; //Valid but not nice.

6TJOHBQMVSBM
MJLFentries
TFFNTUPNBLFTFOTF
TJODFUIFBSSBZIPMETNPSF
UIBOPOFFMFNFOU)PXFWFS
QSPHSBNNFSTGJOEUIBUUIFJSQSPHSBNTPGUFOSFBE
CFUUFSJGUIFZVTFBTJOHVMBSGPSNGPSBOBSSBZOBNF

MJLFUIFGPMMPXJOH
Species[] entry = new Species[20]; //Nicer.

Reading an array
length


488

CHAPTER 7 / Arrays

5IF SFBTPO UIBU UIF TJOHVMBS GPSN XPSLT CFUUFS IFSF JT UIBU
 XIFO UIF BSSBZ
OBNF JT VTFE JO TPNF TPSU PG DPNQVUBUJPO
 UIF OBNF SFGFST UP POMZ POF
FMFNFOU 5IF FYQSFTTJPO entry[2] JT B TJOHMF FMFNFOU PG UIF BSSBZ
 BT JO B
statement such as
System.out.println("The entry is " + entry[2]);

5IFVTFPGTJOHVMBSOBNFTGPSBSSBZTJTOPUBOBCTPMVUFSVMF4PNFUJNFT
JU NBLFT TFOTF UP VTF QMVSBM OBNFT 'PS FYBNQMF
 JG BO JOEFYFE WBSJBCMF
contains the number of hours worked by employee number n
 UIF QMVSBM
form hours[n] makes sense. The only sure test of whether to use a singular or
QMVSBMOBNFJTUPDPOTJEFSIPXBOJOEFYFEWBSJBCMFXPVMESFBEJOUIFDPOUFYU
of your Java code.



The Instance Variable length
"O BSSBZ JT B LJOE PG PCKFDU
 BOE MJLF PUIFS PCKFDUT
 JU NJHIU IBWF JOTUBODF
WBSJBCMFT "T JU UVSOT PVU
 BO BSSBZ IBT POMZ POF QVCMJD JOTUBODF WBSJBCMF

namely the variable length
 XIJDI JT FRVBM UP UIF MFOHUI PG UIF BSSBZ 'PS
FYBNQMF
JGZPVDSFBUFBOBSSBZCZXSJUJOH
The array e has a
length of e.length

Species[] entry = new Species[20];
entry.length IBT B WBMVF PG  #Z VTJOH UIF JOTUBODF WBSJBCMF length
instead of a literal like 20
 ZPV DBO NBLF ZPVS QSPHSBN DMFBSFS BOE NPSF
general. A name like entry.length means more to a reader of your program

UIBOBOVNCFSXIPTFNFBOJOHNBZOPUBMXBZTCFPCWJPVT*OBEEJUJPO
JG
ZPVMBUFSEFDJEFUPDIBOHFUIFTJ[FPGUIFBSSBZ
ZPVIBWFOPOFFEUPDIBOHF
occurrences of entry.length. Note that lengthJTGJOBM
TPJUTWBMVFDBOOPU
be changed.

GOTCHA


Assigning a Value to the Instance Variable length

Your program cannot assign a value to the instance variable length
 BT JU JT
BGJOBMWBSJBCMF'PSFYBNQMF
UIFGPMMPXJOHBUUFNQUUPDIBOHFUIFTJ[FPGBO
array is invalid:
entry.length = 10; //Illegal!



*O -JTUJOH  XF IBWF SFXSJUUFO UIF QSPHSBN JO -JTUJOH  VTJOH
the instance variable length. We have also read the size of the array
temperature from the user into the variable size *O UIJT FYBNQMF
 XF
could use size instead of temperature.length )PXFWFS
 TJODF size is
OPUGJOBM
JUTWBMVFDBODIBOHFBOETPNJHIUOPUBMXBZTFRVBMUIFWBMVFPG
temperature.length.


7.1 Array Basics

LISTING 7.2

An Array of Temperatures—Revised (part 1 of 2)

/**
Reads temperatures from the user and shows which are above

and which are below the average of all the temperatures.
*/
import java.util.Scanner;
public class ArrayOfTemperatures2
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many temperatures do you have?");
int size = keyboard.nextInt( );
double[] temperature = new double[size];
// Read temperatures and compute their average:
System.out.println("Enter " + temperature.length +
" temperatures:");
double sum = 0;
for (int index = 0; index < temperature.length; index++)
{
temperature[index] = keyboard.nextDouble();
sum = sum + temperature[index];
}
double average = sum / temperature.length;
System.out.println("The average temperature is " +
average);
// Display each temperature and its relation to the
// average:
System.out.println("The temperatures are");
for (int index = 0; index < temperature.length; index++)
{
if (temperature[index] < average)
System.out.println(temperature[index] +

" below average");
else if (temperature[index] > average)
System.out.println(temperature[index] +
" above average");
else //temperature[index] == average
System.out.println(temperature[index] +
" the average");
}
System.out.println("Have a nice week.");
}
}

(continued)

489


490

CHAPTER 7 / Arrays

LISTING 7.2 An Array of Temperatures—Revised (part 2 of 2)
Sample Screen Output
How many temperatures do you have?
3
Enter 3 temperatures:
32
26.5
27
The average temperature is 28.5

The temperatures are
32.0 above average
26.5 below average
27.0 below average
Have a nice week.

■ PROGRAMMING TIP

Use a for Loop to Step Through
an Array

The for statement is the perfect mechanism for stepping through the elements
PGBOBSSBZ'PSFYBNQMF
UIFGPMMPXJOH forMPPQGSPN-JTUJOHJMMVTUSBUFT
one way to step through an array:
for (int index = 0; index {
temperature[index] = keyboard.nextDouble();
sum = sum + temperature[index];
}

Another way to step through an entire array—after its elements have been
HJWFO WBMVFT‰VTFT UIF GPSFBDI TUBUFNFOU UIBU XF JOUSPEVDFE JO $IBQUFS 
'PSFYBNQMF
UIFMBTUMPPQJO-JTUJOHUIBUEJTQMBZTUIFWBMVFTJOUIFBSSBZ
temperature can be revised as follows:
for (int value : temperature)
{
if (value < average)
System.out.println(value + " below average.");

else if (value > average)
System.out.println(value + " above average.");
else //value == average
System.out.println(value + " the average.");
}




7.1 Array Basics

491

More About Array Indices
:PVLOPXUIBUUIFJOEFYPGUIFGJSTUFMFNFOUJOBOZ+BWBBSSBZJT5IFMBTU
WBMJEJOEFYPGBOBSSBZXIPTFMFOHUIJTn is n¦*OQBSUJDVMBS
UIFMBTUWBMJE
JOEFYPGUIFBSSBZtemperature is temperature.length - 1.
An easy mistake to make when programming with arrays is to use an
JOEFYFE FYQSFTTJPO UIBU FWBMVBUFT UP BO JOWBMJE BSSBZ JOEFY 'PS FYBNQMF

consider the following array declaration:
double[] entry = new double[5];

&WFSZJOEFYWBMVFGPSUIFBSSBZ entryNVTUCFPOFPGUIFGJWFJOUFHFST




PS'PSFYBNQMF

JGZPVSQSPHSBNDPOUBJOTUIFJOEFYFEWBSJBCMFentry[n + 2]

UIFWBMVFPGUIFJOEFY n + 2NVTUCFPOFPGUIFTFGJWFJOUFHFST*GBOJOEFY
FYQSFTTJPOFWBMVBUFTUPTPNFJOUFHFSPUIFSUIBOUISPVHIPOFMFTTUIBOUIF
MFOHUIPGUIFBSSBZ
UIFJOEFYJTTBJEUPCFout of bounds or invalid. If your Beware of invalid
DPEFVTFTBOJOEFYFYQSFTTJPOUIBUJTPVUPGCPVOET
ZPVSDPEFXJMMDPNQJMF indices
XJUIPVUBOZFSSPSNFTTBHF
CVUZPVXJMMHFUPOFXIFOZPVSVOZPVSQSPHSBN

REMEMBER Array Indices Must Be Within Bounds to Be Valid
Since the index of the first element in a Java array is always 0, the last
index number is not the length of the array, but is one less than the
length of the array. Be sure that your indices stay within this range.

One common way that array indices go out of bounds is when an arrayQSPDFTTJOHMPPQJTJUFSBUFEPOFUPPNBOZUJNFT'PSFYBNQMF
MFUTDPOTJEFSB
MPPQUIBUGJMMTBOBSSBZ4VQQPTFXFXBOUUPSFBEBTFRVFODFPGOPOOFHBUJWF
OVNCFSTGSPNUIFLFZCPBSE
VTJOHBOFHBUJWFOVNCFSBTBTFOUJOFMWBMVFBU
the end of the data. We might use the following code:
System.out.println("Enter a list of nonnegative integers.");
System.out.println("Place a negative integer at the end.");
int[] list = new int[10];
Scanner keyboard = new Scanner(System.in);
int number = keyboard.nextInt();
int i = 0;
while (number >= 0)
{

list[i] = number;
i++;
number = keyboard.nextInt();
}

*GUIFVTFSFOUFSTNPSFOVNCFSTUIBODBOGJUJOUIFBSSBZ
UIJTDPEFQSPEVDFT
BOBSSBZJOEFYUIBUJTPVUPGCPVOET


492

CHAPTER 7 / Arrays

A better version of the preceding while loop is the following:
while ( (i <list.length) && (number >= 0) )
{
list[i] = number;
i++;
number = keyboard.nextInt();
}
if (number >= 0)
{
System.out.println("Could not read in all the numbers.");
System.out.println("Only able to read" + list.length +
" numbers.");
}

This whileMPPQXJMMFOEJGUIFBSSBZCFDPNFTGVMM
CFDBVTFXFFOTVSFUIBUUIF

JOEFYi is less than list.length.

GOTCHA

Array Index Out of Bounds

"O BSSBZ JOEFY UIBU JT MFTT UIBO  PS HSFBUFS UIBO PS FRVBM UP UIF TJ[F PG UIF
BSSBZXJMMDBVTFBOFSSPSNFTTBHFEVSJOHQSPHSBNFYFDVUJPO

4VQQPTFUIBUZPVXBOUUPOVNCFSUIFEBUBTUPSFEJOBOBSSBZTUBSUJOHXJUI
1FSIBQT ZPVS DPNQBOZT FNQMPZFFT BSF OVNCFSFE TUBSUJOH XJUI  #VU +BWB
BMXBZTCFHJOTBOBSSBZBUJOEFY0OFXBZUPIBOEMFUIJTTJUVBUJPOJTUPIBWF
ZPVSDPEFSFDPODJMFUIFBSSBZJOEJDFTXJUIUIFFYJTUJOHOVNCFSJOHTDIFNF'PS
FYBNQMF
ZPVNJHIUVTFDPEFTVDIBTUIFGPMMPXJOHJOBQBZSPMMQSPHSBN

Adjusting code
to deal with 0
indices

public static final int NUMBER_OF_EMPLOYEES = 100;
. . .
int[] hours = new int[NUMBER_OF_EMPLOYEES];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter hours worked for each employee:");
for (int index = 0; index < hours.length; index++);
{
System.out.println("Enter hours for employee " +
(index + 1));
hours[index] = keyboard.nextInt();

}

8JUIUIJTDPEF
UIFFNQMPZFFTBSFOVNCFSFEUISPVHI
CVUUIFJSIPVST
worked are stored in elements hours[0] through hours[99].
4JUVBUJPOT MJLF UIJT POF NJHIU DPOGVTF ZPV
 IPXFWFS
 MFBEJOH UP NJTUBLFT
JO ZPVS QSPHSBN 0WFSBMM
 UIF DPEF XJMM CF FBTJFS UP VOEFSTUBOE JG UIF UXP
numbering schemes match. You can achieve this by rewriting the previous code
UPJODSFBTFUIFTJ[FPGUIFBSSBZCZBOEJHOPSFUIFFMFNFOUBUJOEFY
BTGPMMPXT


7.1 Array Basics
int[] hours = new int[NUMBER_OF_EMPLOYEES + 1];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter hours worked for each employee:");
for (int index = 1; index {
System.out.println("Enter hours for employee" + index);
hours[index] = keyboard.nextInt();
}

8JUIUIJTSFWJTFEDPEF
UIFFNQMPZFFTBSFTUJMMOVNCFSFEUISPVHI
CVU
their hours worked are stored in the elements hours[1] through hours[100].

We do not use hours[0]
BOETJODFUIFTJ[FPGUIFBSSBZJTJOTUFBEPG

hours[100] is valid.
Note that the last valid value of index is hours.length − 1
BTJUXBTJO
PVSGJSTUWFSTJPOPGUIJTDPEF)PXFWFS
 hours.length here is one larger than
it was earlier. Replacing
index < hours.length

in the for statement with
index <= NUMBER_OF_EMPLOYEES

JT MJLFMZ UP CF DMFBSFS UP NPTU QFPQMF )PXFWFS
 JG PUIFS QSPHSBNNFST BSF
HPJOHUPCFMPPLJOHBUZPVSDPEF
UIFZNBZCFFYQFDUJOHBWBMVFUPCFTUPSFE
BUJOEFY5IFCPUUPNMJOFJTUIBUBMMQSPHSBNNFSTDPMMBCPSBUJOHPOBQSPKFDU
should use the same coding practices or confusion and errors may result.

■ PROGRAMMING TIP

Don’t Be Afraid to Waste an Element
in an Array

*O PVS QSFWJPVT FYBNQMF
 XF OFWFS VTF hours[0] :FT
 XF iXBTUFEw BO BSSBZ
FMFNFOU

 CVU XF BMTP NBEF PVS DPEF FBTJFS UP XSJUF BOE UP VOEFSTUBOE "T B
SFTVMU
XFMJLFMZXJMMNBLFGFXFSNJTUBLFT)PXFWFS
PUIFSQSPHSBNNFSTXIP
may be working with your code should be aware of your coding practice. In
+BWB
UIFBNPVOUPGNFNPSZXFXBTUFEJTOPUTJHOJGJDBOU&WFOJGXFDSFBUFBO
BSSBZPGMBSHFPCKFDUT
+BWBTUPSFTPOMZUIFBEESFTTFTPGUIFPCKFDUTJOUIFBSSBZ
5IJTNJHIUOPUCFUIFDBTFGPSPUIFSQSPHSBNNJOHMBOHVBHFT'PSFYBNQMF
$


XPVMETUPSFUIFPCKFDUJUTFMG
OPUJUTBEESFTT
JOUIFBSSBZ8BTUJOHBMPDBUJPOJOB
$

BSSBZNJHIUCFNPSFTJHOJGJDBOUUIBOEPJOHTPJOB+BWBQSPHSBN


■ PROGRAMMING TIP

Get Used to Index Values That Are 0

5IFJOEFYPGUIFGJSTUFMFNFOUJOBOBSSBZJT+BWBQSPHSBNNFSTLOPXUIJT6OMFTT
your application gives you a good reason to adjust your code so that you can ignore
UIJT JOEFY
 EPOU 5IF QSFWJPVT FYBNQMF TIPXFE BO BEKVTUNFOU UIBU BMJHOT UXP
OVNCFSJOH TZTUFNT

 SFEVDJOH DPOGVTJPO BOE NBLJOH FSSPST MFTT MJLFMZ )PXFWFS

BEKVTUJOHZPVSDPEFUPBWPJEVTJOHBJOEFYTIPVMEnot be a routine practice.


493

Ignoring the
element at index 0


494

CHAPTER 7 / Arrays

Initializing Arrays
"O BSSBZ DBO CF JOJUJBMJ[FE BU UIF UJNF UIBU JU JT EFDMBSFE 5P EP UIJT
 ZPV
FODMPTF UIF WBMVFT GPS UIF JOEJWJEVBM JOEFYFE WBSJBCMFT JO CSBDFT BOE QMBDF
UIFNBGUFSUIFBTTJHONFOUPQFSBUPS
BTJOUIFGPMMPXJOHFYBNQMF
double[] reading = {3.3, 15.8, 9.7};

5IFTJ[FPGUIFBSSBZ‰UIBUJT
JUTMFOHUI‰JTTFUUPUIFNJOJNVNUIBUXJMMIPME
UIFHJWFOWBMVFT4PUIJTJOJUJBMJ[JOHEFDMBSBUJPOJTFRVJWBMFOUUPUIFGPMMPXJOH
statements:
double[] reading = new double[3];
reading[0] = 3.3;
reading[1] = 15.8;

reading[2] = 9.7;

Explicit
initialization is
safer than default
initialization

*GZPVEPOPUJOJUJBMJ[FUIFFMFNFOUTPGBOBSSBZ
UIFZNJHIUBVUPNBUJDBMMZ
CFJOJUJBMJ[FEUPBEFGBVMUWBMVFGPSUIFCBTFUZQF'PSFYBNQMF
JGZPVEPOPU
JOJUJBMJ[FBOBSSBZPGJOUFHFST
FBDIFMFNFOUPGUIFBSSBZXJMMCFJOJUJBMJ[FEUP
)PXFWFS
JUJTVTVBMMZDMFBSFSUPEPZPVSPXOFYQMJDJUJOJUJBMJ[BUJPO:PVDBO
JOJUJBMJ[FBOBSSBZFJUIFSCZVTJOHUIFCSBDFT
BTXFKVTUEFTDSJCFE
CZSFBEJOH
WBMVFT EJSFDUMZ JOUP BSSBZ FMFNFOUT
 PS CZ BTTJHOJOH WBMVFT
 BT XF EP JO UIF
following for loop:
int[] count = new int[100];
for (int i = 0; i < 100; i++)
count[i] = 0;

S E L F -TE S T QU ESTI ONS
  8IBUPVUQVUXJMMCFQSPEVDFECZUIFGPMMPXJOHDPEF
int[] anArray = new int[10];
for (int i = 0; i

anArray[i] = 2 * i;
for (int element : anArray)
System.out.print(element + " ");
System.out.println();

  8IBUPVUQVUXJMMCFQSPEVDFECZUIFGPMMPXJOHDPEF
char[] vowel = {'a', 'e', 'i', 'o', 'u'};
for (int index = 0; index System.out.println(vowel[index]);


7.2 Arrays in Classes and Methods

  8IBUPVUQVUXJMMCFQSPEVDFECZUIFGPMMPXJOHDPEF
double tide[] = {12.2, −7.3, 14.2, 11.3};
System.out.println("Tide 1 is " + tide[1]);
System.out.println("Tide 2 is " + tide[2]);

  $POTJEFSUIFGPMMPXJOHBSSBZ
int[] a = new int[10];

8IBUJTUIFMBTUJOEFYPGa 8IBUJTUIFWBMVFPGa.length
  8IBUJTXSPOHXJUIUIFGPMMPXJOHDPEFUPJOJUJBMJ[FBOBSSBZb
int[] b = new int[10];
for (int i = 1; i <= b.length; i++)
b[i] = 5 * i;

  8SJUFBDPNQMFUF+BWBQSPHSBNUIBUSFBETWBMVFTPGUZQFdouble from the
LFZCPBSEJOUPBOBSSBZ%JTQMBZUIFMBTUUI
OVNCFSSFBE5IFOEJTQMBZ

UIFOVNCFSTJOUIFBSSBZBOEIPXNVDIFBDIOVNCFSEJGGFSTGSPNUIFUI
OVNCFS SFBE 'PS FYBNQMF
 JG UIF MBTU WBMVF UZQFE CZ UIF VTFS JT 
 UIF
EJGGFSFODFCFUXFFOUIFBSSBZFMFNFOUBOEJT¦*GBOBSSBZFMFNFOU
JT
UIFEJGGFSFODFJT"TTVNFUIBUUIFVTFSFOUFSTOVNCFST
POFQFS
MJOF
BUUIFLFZCPBSE:PVOFFEOPUHJWFFMBCPSBUFJOTUSVDUJPOTUPUIFVTFS

7.2 ARRAYS IN CLASSES AND METHODS
A little more than kin, and less than kind.
—WILLIAM SHAKESPEARE, HAMLET

Arrays can be used as instance variables in classes. Methods can have an
JOEFYFEWBSJBCMFPSBOFOUJSFBSSBZBTBOBSHVNFOUBOEDBOSFUVSOBOBSSBZ*O
TIPSU
BSSBZTDBOCFVTFEXJUIDMBTTFTBOENFUIPETKVTUBTPUIFSPCKFDUTDBO
We begin with a case study that uses an array as an instance variable in a class.

CASE STUDY Sales Report
*O UIJT DBTF TUVEZ
 XF XJMM XSJUF B QSPHSBN UP HFOFSBUF TBMFT SFQPSUT GPS B
company’s team of sales associates. The company wants to easily see which The task’s
specification
associate or associates have the highest sales and to know how the sales of
each associate compare to the average.
4JODFXFOFFEUPSFDPSEBOBNFBOEUIFTBMFTGJHVSFTGPSFBDIBTTPDJBUF
XF

can design a class for a single sales associate that holds these two data items.
Our class can perform input and output and have a reasonable complement
of accessor and mutator methods. This class definition is rather routine and is
TIPXOJO-JTUJOH

495


496

CHAPTER 7 / Arrays

LISTING 7.3 Sales Associate Class
import java.util.Scanner;
/**
Class for sales associate records.
*/
public class SalesAssociate
{
private String name;
private double sales;
public SalesAssociate()
{
name = "No record";
sales = 0;
}
public SalesAssociate(String initialName, double initialSales)
{
set(initialName, initialSales);
}

public void set(String newName, double newSales)
{
name = newName;
sales = newSales;
}
public void readInput()
{
System.out.print("Enter name of sales associate: ");
Scanner keyboard = new Scanner(System.in);
name = keyboard.nextLine();
System.out.print("Enter associate's sales: $");
sales = keyboard.nextDouble();
}
public void writeOutput()
{
System.out.println("Name: " + name);
System.out.println("Sales: $" + sales);
}
public String getName()
{
return name;
}
public double getSales()
{
return sales;
}
}


7.2 Arrays in Classes and Methods


497

Our program will need an array to keep track of the data for all sales
associates. It will also need to record the highest sales and the average sales.
5IFSFGPSF
XFXJMMOFFEUPEFTJHOBOPUIFSDMBTT8FDBOHJWFPVSOFXDMBTTUIF
following instance variables to record the desired data:
private double highestSales;
private double averageSales;
private SalesAssociate[] team;

The instance
variables

We need to know the number of associates. This number will be the
same as team.length
 CVU IBWJOH B TFQBSBUF XFMMOBNFE WBSJBCMF GPS
UIF OVNCFS PG BTTPDJBUFT JT B HPPE JEFB 4P MFUT JODMVEF UIF GPMMPXJOH
instance variable:
private int numberOfAssociates; //Same as team.length

The job of our program breaks down into these main subtasks:
1. Get ready.
2. Obtain the data.
  $PNQVUFTPNFTUBUJTUJDTVQEBUFUIFJOTUBODFWBSJBCMFT

  %JTQMBZUIFSFTVMUT
8FTIPVMEOBNFPVSOFXDMBTTBOEJUTNFUIPET5PPSHBOJ[FPVSUIPVHIUT
XF

DBOESBXUIFDMBTTEJBHSBNTIPXOJO'JHVSF 5IVT
XFLOPXUIBUPVSDMBTT
will look like this:
public class SalesReporter
{
private double highestSales;
private double averageSales;
private SalesAssociate[] team;
private int numberOfAssociates; //Same as team.length
public static void main(String[ ] args)
{
SalesReporter clerk = new SalesReporter();
clerk.getData();
clerk.computeStats();
clerk.displayResults();
}
<More stuff needs to be added here.>
}

"MMUIBUSFNBJOTJTUPXSJUFUIFUISFFNFUIPET
getData, computeStats, and
displayResults and to test and debug the program. We will tackle the three
methods in order.

The program’s
subtasks


498


CHAPTER 7 / Arrays

FIGURE 7.3 Class Diagram for the Class Sales Reporter

SalesReporter
-

highestSales: double
averageSales: double
team: SalesAssociate[]
numberOfAssociates: int

+ getData(): void
+ computeStats(): void
+ displayResults(): void

The loop in
getData

The input method getData JT SFMBUJWFMZ TUSBJHIUGPSXBSE
 FTQFDJBMMZ
since we have an input method for objects of the class SalesAssociate.
"GUFS XF SFBE UIF OVNCFS PG BTTPDJBUFT
 XF DBO XSJUF UIF GPMMPXJOH CBTJD
input loop:
for (int i = 1; i <= numberOfAssociates; i++)
{
System.out.println("Enter data for associate number" + i);
team[i].readInput();
}


Associate i is in
team[i]

"MUIPVHI UIF BSSBZ JOEJDFT CFHJO BU 
 BOE UIF BTTPDJBUFT BSF OVNCFSFE
TUBSUJOHXJUI
XFIBWFVTFE team[i] for associate i5IBUJT
XFEFDJEFEUP
ignore team[0]5IVT
XFOFFEUPBMMPDBUFBOFYUSBMPDBUJPOJOUIFBSSBZ
BT
follows:
team = new SalesAssociate[numberOfAssociates + 1];

4JODFXFSFBE numberOfAssociates in getData
XFXJMMQMBDFUIJTTUBUFNFOU
in that method as well.
#VUBOPUIFSQSPCMFNSFNBJOT8IFOXFUFTUUIFQSFWJPVTMPPQ
XFXJMMHFU
BOFSSPSNFTTBHFTBZJOHTPNFUIJOHBCPVUBiOVMMQPJOUFSw5IJTQSPCMFNBSJTFT
because the base type of the array team JT B DMBTT UZQF 5P TFF UIF QSPCMFN

DPOTJEFSBOPUIFSTJUVBUJPOGJSTU4VQQPTFXFIBEUIFGPMMPXJOHDPEF
SalesAssociate s;
s.readInput();

5IJTDPEFXPVMEQSPEVDFUIFTBNFFSSPSNFTTBHFSFHBSEJOHBiOVMMQPJOUFSw
The problem is that the variable s is just a name; it does not yet reference any



7.2 Arrays in Classes and Methods

object of the class SalesAssociate. The preceding code omitted the usual use
of new. The code should be
SalesAssociate s = new SalesAssociate();
s.readInput();

5IFJOEFYFEWBSJBCMF team[i]JTBMTPBWBSJBCMFPGBDMBTTUZQF
BOETPJU
is also just a name. You need to assign a SalesAssociate object to team[i]
CFGPSFFYFDVUJOH
team[i].readInput();

5IVT
XFOFFEUPBEEUIFGPMMPXJOHTUBUFNFOUUPPVSMPPQ
team[i] = new SalesAssociate();

The complete definition of the method getData with this line inserted is
TIPXOJO-JTUJOH
LISTING 7.4

A Sales Report Program (part 1 of 3)

import java.util.Scanner;
/**
Program to generate sales report.
*/
public class SalesReporter
{

private double highestSales;
private double averageSales;
private SalesAssociate[] team;

The main method is at
the end of the class.

//The array object is
//created in getData.
private int numberOfAssociates; //Same as team.length
/**
Reads the number of sales associates and data for each one.
*/
public void getData()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter number of sales associates:");
numberOfAssociates = keyboard.nextInt();
team = new SalesAssociate[numberOfAssociates + 1];
for (int i = 1; i <= numberOfAssociates; i++)
Array object
{
created here.
team[i] = new SalesAssociate();
System.out.println("Enter data for associate " + i);
team[i].readInput();
System.out.println();
SalesAssociate
}
objects created here.


}

(continued)

499


×