1. Trang chủ
  2. » Công Nghệ Thông Tin

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

473 73 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Arrays: Sorting and Searching Arrays
Định dạng
Số trang 473
Dung lượng 7,27 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Ebook Java: An introduction to problem solving & programming (Sixth edition) – Part 2 presents the following chapters: Chapter 7 arrays; chapter 8 inheritance, polymorphism and interfaces; chapter 9 exception handling; chapter 10 streams and file I/O; chapter 11 recursion; chapter 12 dynamic data structures and generics; chapter 13 window interfaces using swing; chapter 14 applets and HTML; chapter 15 more swing.

Trang 1

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.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 515

Partially Filled Arrays 523

7.4 SORTING AND SEARCHING ARRAYS 525 Selection Sort 525

Other Sorting Algorithms 529 Searching an Array 531

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.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

7

Chapter Summary 556 Programming Projects 562 Answers to Self-Test Questions 568

Trang 2

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:

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#FDBVTFarrays were used by programmers for many years before classes were

methods

in Java

OBJECTIVES

t %FTDSJCFUIFOBUVSFBOEQVSQPTFPGBOBSSBZt 6TFBSSBZTJOTJNQMF+BWBQSPHSBNT

t %FGJOFNFUIPETUIBUIBWFBOBSSBZBTBQBSBNFUFSt %FGJOFNFUIPETUIBUSFUVSOBOBSSBZ

t 6TFBOBSSBZBTBOJOTUBODFWBSJBCMFJOBDMBTTt 6TFBOBSSBZUIBUJTOPUGJMMFEDPNQMFUFMZt 4FBSDIBOBSSBZGPSBQBSUJDVMBSJUFNt %FGJOFBOEVTFNVMUJEJNFOTJPOBMBSSBZTt *OTFSUUFYUGJFMETBOEUFYUBSFBTJOUPZPVSBQQMFUTt %SBXBSCJUSBSZQPMZHPOTJOZPVSBQQMFUT

PREREQUISITES

This is the first point in this book where you have a significant choice as to

go on in the book and return to this discussion of arrays at a later time You

480

with his own values.

Trang 3

UPBSSBZTGPSTPNFPGUIFFYBNQMFT

be familiar with the material in all of the previous chapters before reading the

remaining sections of this chapter

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

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

The obvious answer is to use seven variables of type double This is a bit

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

have the same data type

Trang 4

Creating and Accessing Arrays

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]

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

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 typedouble

temperature[3] = 32;

temperature[6] = temperature[3] + 5;

System.out.println(temperature[6]);

8IFOXFUIJOLPGUIFTFJOEFYFEWBSJBCMFTBTCFJOHHSPVQFEUPHFUIFSJOUPPOFtemperatureXJUIPVUVTJOHBOZTRVBSFCSBDLFUT'JHVSFJMMVTUSBUFTUIFBSSBZtemperature

#VUUIFTFTFWFOWBSJBCMFTBSFNPSFUIBOKVTUTFWFOQMBJOPMEWBSJBCMFTPGtype double 5IF OVNCFS JO TRVBSF CSBDLFUT JT QBSU PG UIF OBNF PG FBDI PGDBOVTFBOZFYQSFTTJPOUIBUFWBMVBUFTUPBOJOUFHFSUIBUJTBUMFBTUBOE‰GPS

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();

Trang 5

the array temperature

System.out.println("Enter 7 temperatures:");

for (int index = 0;index < 7; index++)

temperature[index] = keyboard.nextDouble();

System.out.println("The 7 temperatures are:");

for (int index = 0; index < 7; index++)

System.out.print(temperature[index] + " ");

System.out.println( );

5IFQSPHSBNJO-JTUJOHTIPXTBOFYBNQMFUIBUVTFTPVSTBNQMFBSSBZ

program uses for loops similar to the ones we just considered

4 3

2 1

/**

Reads 7 temperatures from the user and shows which are above

and which are below the average of the 7 temperatures.

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)

Trang 6

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.

Trang 7

Array Details

You create an array in the same way that you would create an object of a class

type using the operation new

creating an array of elements of type Base_Type

Base_Type[] Array_Name = new Base_Type[Length];

pressureUIBUJTFRVJWBMFOU

UPWBSJBCMFTPGUZQFint:

int[] pressure = new int[100];

int[] pressure;

pressure = new int[100];

The first step declares as an

array of integers The second

step allocates enough memory

GPSUIFBSSBZUPIPMEVQUP

integers

The type for the array

elements is called the base

type of the array In this

int.The number of elements in

an array is called the length,

size, or capacity of the array

4P UIJT TBNQMF BSSBZpressure

variables pressure[0]through pressure[99] Note that because the indices

pressurevariablepressure[100]

a class type The following statement creates an array named entry whose

Species[] entry = new Species[3];

This array is a collection of the three variables entry[0] entry[1]

entry[2] Species

The number of elements in an array is its length

ASIDE Alternative Syntax for Declaring

an Array

Although we do not encourage its use, there

is an alternative syntax for array declarations that you may encounter You can write the square brackets after the variable instead

of after the base type, as in the following example:

char alphabet[];

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

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)

Trang 8

NUMBER_OF_READINGS instead of

XIFOZPVDSFBUFUIFBSSBZpressure:public static final int NUMBER_OF_READINGS = 100;

int[] pressure = new int[NUMBER_OF_READINGS];

FYFDVUJPO UJNF 4P JG ZPV EP OPU LOPX IPX MBSHF UP NBLF BO BSSBZ XIFOfollows:

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

int[] pressure;

declares—but does not allocate memory for— pressure as an array of HFST

inte-pressure = new int[100];

allocates memory for the array pressure PGJOUFHFST

pressure[3] in the following two lines is an indexed variable:

Trang 9

System.out.println("How many temperatures do you have?");

int size = keyboard.nextInt();

double[] temperature = new double[size];

:PVDBOBMTPVTFBOZFYQSFTTJPOUIBUFWBMVBUFTUPBOBQQSPQSJBUFJOUFHFS

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] point + 3FWBMVBUFTUP

'JHVSFJMMVTUSBUFTTPNFPGUIFNPTUDPNNPOUFSNTVTFEXIFOSFGFSSJOH

to arrays Notice that the word element has two meanings It can be used to

SFGFSUPBOJOEFYFEWBSJBCMFBTXFMMBTUPUIFWBMVFPGBOJOEFYFEWBSJBCMF

Reading an array length

Array name

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

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

Index (also called a subscript)

Trang 10

The Instance Variable length

namely the variable length

Species[] entry = new Species[20];

entry.length IBT B WBMVF PG  #Z VTJOH UIF JOTUBODF WBSJBCMFlengthinstead of a literal like 20

general A name like entry.length means more to a reader of your program

occurrences of entry.length Note that length

be changed

FMFNFOU 5IF FYQSFTTJPOentry[2]

statement such asSystem.out.println("The entry is " + entry[2]);

5IFVTFPGTJOHVMBSOBNFTGPSBSSBZTJTOPUBOBCTPMVUFSVMF4PNFUJNFTcontains the number of hours worked by employee number n

formhours[n] makes sense The only sure test of whether to use a singular or QMVSBMOBNFJTUPDPOTJEFSIPXBOJOEFYFEWBSJBCMFXPVMESFBEJOUIFDPOUFYU

The array e has a

length of e.length

GOTCHA Assigning a Value to the Instance Variable length

Your program cannot assign a value to the instance variable lengtharray is invalid:

*O -JTUJOH  XF IBWF SFXSJUUFO UIF QSPHSBN JO -JTUJOH  VTJOHthe instance variable length We have also read the size of the array temperature from the user into the variable size

temperature.length

Trang 11

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.

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:

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++)

Trang 12

PROGRAMMING TIP Use a for Loop to Step Through

an Array

Thefor statement is the perfect mechanism for stepping through the elements

forMPPQGSPN-JTUJOHJMMVTUSBUFTone way to step through an array:

for (int index = 0; index <temperature.length; 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 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.");

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.

Trang 13

More About Array Indices

:PVLOPXUIBUUIFJOEFYPGUIFGJSTUFMFNFOUJOBOZ+BWBBSSBZJT5IFMBTU

JOEFYPGUIFBSSBZtemperature is temperature.length - 1

An easy mistake to make when programming with arrays is to use an

consider the following array declaration:

double[] entry = new double[5];

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

array-MPPQUIBUGJMMTBOBSSBZ4VQQPTFXFXBOUUPSFBEBTFRVFODFPGOPOOFHBUJWF

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();

Trang 14

A better version of the preceding while loop is the following:

while ( (i <list.length) && (number >= 0) ) {

System.out.println("Could not read in all the numbers."); System.out.println("Only able to read" + list.length + " numbers.");

}ThiswhileJOEFYi is less than list.length

GOTCHA Array Index Out of Bounds

"OBSSBZJOEFYUIBUJTMFTTUIBOPSHSFBUFSUIBOPSFRVBMUPUIFTJ[FPGUIF

4VQQPTFUIBUZPVXBOUUPOVNCFSUIFEBUBTUPSFEJOBOBSSBZTUBSUJOHXJUI1FSIBQT ZPVS DPNQBOZT FNQMPZFFT BSF OVNCFSFE TUBSUJOH XJUI  #VU +BWBBMXBZTCFHJOTBOBSSBZBUJOEFY0OFXBZUPIBOEMFUIJTTJUVBUJPOJTUPIBWFZPVSDPEFSFDPODJMFUIFBSSBZJOEJDFTXJUIUIFFYJTUJOHOVNCFSJOHTDIFNF'PS

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();

}

worked are stored in elements hours[0] through hours[99]

numbering schemes match You can achieve this by rewriting the previous code

Adjusting code

to deal with 0

indices

Trang 15

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 <hours.length; index++);

{

System.out.println("Enter hours for employee" + index);

hours[index] = keyboard.nextInt();

}

their hours worked are stored in the elements hours[1] through hours[100]

We do not use hours[0]

hours[100] is valid

Note that the last valid value of index is hours.length − 1

hours.length here is one larger than

it was earlier Replacing

PROGRAMMING TIP Don’t Be Afraid to Waste an Element

your application gives you a good reason to adjust your code so that you can ignore

BEKVTUJOHZPVSDPEFUPBWPJEVTJOHBJOEFYTIPVMEnot be a routine practice.

Trang 16

Initializing Arrays

FODMPTF UIF WBMVFT GPS UIF JOEJWJEVBM JOEFYFE WBSJBCMFT JO CSBDFT BOE QMBDF

double[] reading = {3.3, 15.8, 9.7};

UIFHJWFOWBMVFT4PUIJTJOJUJBMJ[JOHEFDMBSBUJPOJTFRVJWBMFOUUPUIFGPMMPXJOHstatements:

double[] reading = new double[3];

reading[0] = 3.3;

reading[1] = 15.8;

reading[2] = 9.7;

followingfor loop:

int[] count = new int[100];

for (int i = 0; i < 100; i++) count[i] = 0;

for (int i = 0; i <anArray.length; 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 <vowel.length; index++) System.out.println(vowel[index]);

Trang 17

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

UIFOVNCFSTJOUIFBSSBZBOEIPXNVDIFBDIOVNCFSEJGGFSTGSPNUIFUI

EJGGFSFODFCFUXFFOUIFBSSBZFMFNFOUBOEJT¦*GBOBSSBZFMFNFOU

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

We begin with a case study that uses an array as an instance variable in a class

CASE STUDY Sales Report

company’s team of sales associates The company wants to easily see which

associate or associates have the highest sales and to know how the sales of

each associate compare to the average

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

The task’s specification

Trang 18

LISTING 7.3 Sales Associate Class

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;

} }

Trang 19

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

following instance variables to record the desired data:

private double highestSales;

private double averageSales;

private SalesAssociate[] team;

We need to know the number of associates This number will be the

same as team.length

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

  %JTQMBZUIFSFTVMUT

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)

The program’s subtasks

Trang 20

FIGURE 7.3 Class Diagram for the Class Sales Reporter

The input method getDatasince we have an input method for objects of the class SalesAssociate.input loop:

for (int i = 1; i <= numberOfAssociates; i++) {

System.out.println("Enter data for associate number" + i); team[i].readInput();

}

team[i] for associate iignore team[0]

follows:

team = new SalesAssociate[numberOfAssociates + 1];

4JODFXFSFBEnumberOfAssociates in getData

in that method as well

BOFSSPSNFTTBHFTBZJOHTPNFUIJOHBCPVUBiOVMMQPJOUFSw5IJTQSPCMFNBSJTFTbecause the base type of the array team

DPOTJEFSBOPUIFSTJUVBUJPOGJSTU4VQQPTFXFIBEUIFGPMMPXJOHDPEF

SalesAssociate s;

s.readInput();

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

The loop in

getData

Associate i is in

team[i]

Trang 21

object of the class SalesAssociate The preceding code omitted the usual use

ofnew The code should be

SalesAssociate s = new SalesAssociate();

team[i] = new SalesAssociate();

The complete definition of the method getData with this line inserted is

private double highestSales;

private double averageSales;

private SalesAssociate[] team; //The array object is

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++)

{

team[i] = new SalesAssociate();

System.out.println("Enter data for associate " + i);

SalesAssociate

objects created here.

(continued)

Trang 22

LISTING 7.4 A Sales Report Program (part 2 of 3)

/**

Computes the average and highest sales figures.

Precondition: There is at least one salesAssociate.

double sum = nextSales;

for (int i = 2; i <= numberOfAssociates; i++) {

System.out.println("The following had the highest sales:");

for (int i = 1; i <= numberOfAssociates; i++) {

double nextSales = team[i].getSales();

if (nextSales == highestSales) {

for (int i = 1; i <= numberOfAssociates; i++) {

double nextSales = team[i].getSales();

if (team[i].getSales() != highestSales) {

(continued)

Already processed

team[1], so the loop starts with team[2].

Trang 23

LISTING 7.4 A Sales Report Program (part 3 of 3)

team[i].writeOutput();

if (nextSales >= averageSales) System.out.println("$" + (nextSales - averageSales) + " above the average.");

else System.out.println("$" + (averageSales - nextSales) + " below the average.");

Sample Screen Output

Enter number of sales associates:

3

Enter data for associate number 1

Enter name of sales associate: Dusty Rhodes

Enter associate's sales: $36000

Enter data for associate number 2

Enter name of sales associate: Natalie Dressed

Enter associate's sales: $50000

Enter data for associate number 3

Enter name of sales associate: Sandy Hair

Enter associate's sales: $10000

Average sales per associate is $32000.0

The highest sales figure is $50000.0

The following had the highest sales:

Name: Natalie Dressed

Sales: $50000.0

$18000.0 above the average.

The rest performed as follows:

Name: Dusty Rhodes

Sales: $36000.0

$4000.0 above the average.

Name: Sandy Hair

Sales: $10000.0

$22000.0 below the average.

Trang 24

/FYU XF UVSO PVS BUUFOUJPO UP UIF NFUIPEcomputeStats and come up with the following code:

for (int i = 1; i <= numberOfAssociates; i++) {

sum = sum + team[i].getSales();

if (team[i].getSales() > highest)

highestSales = team[i].getSales();//highest sales

average = sum / numberOfAssociates;

sum and highest must be initialized initializehighest

sum and highest to the sales for the first associate This takes one case outside the loop and places

highestSales = team[1].getSales();

double sum = team[1].getSales();

for (int i = 2; i <= numberOfAssociates; i++) {

sum = sum + team[1].getSales();

if (team[i].getSales() > highest)

highestSales = team[i].getSales();//highest sales

//so far.

} average = sum / numberOfAssociates;

three identical method invocations of team[i].getSales() To avoid this

double nextSales = team[1].getSales();

highestSales = nextSales;

double sum = nextSales;

for (int i = 2; i <= numberOfAssociates; i++) {

The complete definition of the method computeStatsJTHJWFOJO-JTUJOH

Trang 25

Indexed Variables as Method Arguments

"OJOEFYFEWBSJBCMFGPSBOBSSBZa a[i]

ZPV DBO VTF BOZ PUIFS WBSJBCMF PG UIF CBTF UZQF PG UIF BSSBZ 4P BO JOEFYFE

WBSJBCMF DBO CF BO BSHVNFOU UP B NFUIPE JO FYBDUMZ UIF TBNF XBZ UIBU BOZ

other variable of the array’s base type can be an argument

variable as an argument to a method The method getAverage takes two

arguments of type int The array nextScore has the base type int

program can use nextScore[i] as an argument to the method getAverage

in the following line from that program:

double possibleAverage = getAverage(firstScore,nextScore[i]);

The variable firstScore is an ordinary variable of type int To help drive

IPNFUIFQPJOUUIBUUIFJOEFYFEWBSJBCMFnextScore[i] can be used just like

any other variable of type int getAverageXPVMECFIBWFJOFYBDUMZ

double possibleAverage = getAverage(nextScore[i],firstScore);

The definition of the method getAverage contains no indication that its

BSHVNFOUT DBO CF JOEFYFE WBSJBCMFT GPS BO BSSBZ PGint The method accepts

arguments of type int

5IFSF JT POF TVCUMFUZ UIBU BQQMJFT UP JOEFYFE WBSJBCMFT XIFO VTFE BT

JTFWBMVBUFEUPEFUFSNJOFFYBDUMZXIJDIJOEFYFEWBSJBCMFJTUIFBSHVNFOU

#FTVSFUPOPUFUIBUBOJOEFYFEWBSJBCMFPGBOBSSBZa a[i]

variable of the base type of the array When a[i] is used as an argument to a

type of the array a

S E L F - T E S T Q U E S T I O N S

  8SJUF TPNF +BWB DPEF UIBU XJMM EFDMBSF BO BSSBZ OBNFEentry that has

SalesAssociatewith three identical records The records use the name "Jane Doe" and

an argument

The value of the index affects the value of the argument

Trang 26

LISTING 7.5 Indexed Variables as Arguments

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter your score on exam 1:");

int firstScore = keyboard.nextInt();

int[] nextScore = new int[3];

for (int i = 0; i < nextScore.length; i++) nextScore[i] = firstScore + 5 * i;

for (int i = 0; i < nextScore.length; i++) {

double possibleAverage = getAverage(firstScore, nextScore[i]); System.out.println("If your score on exam 2 is " + nextScore[i]);

System.out.println("your average will be " + possibleAverage);

} } public static double getAverage(int n1, int n2) {

return (n1 + n2) / 2.0;

} }

Sample Screen Output

Enter your score on exam 1:

Trang 27

such as int double char a[i].

can change the state of the object named by a[i] This is nothing new Just

a[i]

of the array and is handled just like any other variable of that data type

RECAP Indexed Variables as Arguments

An indexed variable can be used as an argument anywhere that a

variable of the array’s base type can be used For example, suppose you

have

double[] a = new double[10];

Indexed variables such as a[3] and a[index] can then be used as

arguments to any method that accepts a value as an argument.

FAQ When can a method change an argument that is an

indexed variable?

Suppose a[i] is an indexed variable of the array a and a[i] is used as an

argument in a method invocation such as

doStuff(a[i]);

Whether the method doStuff can change the array element a[i]

depends on the base type of the array a If the base type of the array a

is a primitive type, such as int , double or char , the method doStuff

receives the value of a[i] , and so cannot change a[i] itself, However,

if the base type of the array a is a class, the method dostuff receives a

reference to a[i] Thus, the method can change the state of the object

named by a[i] , but cannot replace the object with another one (To

review the details on method arguments, see Chapter 5.)

Entire Arrays as Arguments to a Method

:PVIBWFBMSFBEZTFFOUIBUBOJOEFYFEWBSJBCMFPGBOBSSBZDBOCFVTFEBTBO

argument to a method An entire array can also be used as an argument to a

method The way you specify an array parameter in a method definition is

Trang 28

incrementArrayBy2 will accept as its one argument any array whose base type

isdouble:public class SampleClass {

public static void incrementArrayBy2(double[] anArray) {

for (int i = 0; i <anArray.length; i++) anArray[i] = anArray[i] + 2;

} <The rest of the class definition goes here.>

}

length of the array

suppose you have the statementsdouble[] a = new double[10];

double[] b = new double[30];

the elements of the arrays a and b have been given WBMVFT#PUIPGUIFGPMMPXJOHNFUIPEJOWPDBUJPOTare then valid:

There is an alternative syntax for array

parameters, similar to the alternative syntax

for declaring an array You can write the

square brackets after the parameter instead

of after the base type, as in the following

example:

public static void showArray

(char a[])

We do not encourage the use of this

alternative syntax, however.

RECAP Array Parameters

An argument to a method may be an entire array You use the following syntax for the method’s heading:

SYNTAX

public static Return_Type Method_Name(Base_Type[] Param_Name)

You can use other modifiers instead of public and static.

(continued)

Trang 29

REMEMBER Array Parameters Do Not Specify the Array Length

An array parameter in a method’s heading specifies the base type of the

array, but not the length of the array For example, the following method

heading specifies an array of characters as a parameter:

public static void showArray(char[] a)

REMEMBER Characteristics of Array Arguments

public static int getOneElement(char[] anArray, int index)

public void readArray(int[] anotherArray)

Arguments for the Method main

The heading for the main method of a program is as follows:

public static void main(String[] args)

The parameter declaration String[] args indicates that args is an array

WBMVFTBTBOBSHVNFOU#VUXFOFWFSIBWFHJWFOmain an argument when we

main! What’s the TUPSZ

main is a very special sort of invocation that

main is invoked automatically

will automatically be made elements of the array args that is provided to

Trang 30

java TestProgram Sally SmithThis command sets args[0] to "Sally" and args[1] to "Smith" These two JOEFYFEWBSJBCMFTDBOUIFOCFVTFEXJUIJOUIFNFUIPEmain

public class TestProgram {

public static void main(String[] args) {

System.out.println("Hello" + args[0] + " " + args[1]); }

}After running TestProgram using the one-line commandjava TestProgram Josephine Student

the output produced by the program will beHello Josephine Student

#FTVSFUPOPUFUIBUUIFBSHVNFOUUPmain is an array of strings If you want

Integer.parseInt(args[0])4JODFUIFJEFOUJGJFSargs

args

as you change any occurrences of args that also occur in the body of main

args for this parameter

Array Assignment and Equality

kinds of objects we saw before discussing arrays To understand how this the computer’s main memory The important point for this discussion is that

location of the entire array contents can be specified by one memory address.Recall that a variable for an object really contains the memory address of consider the following code:

int[] a = new int[3];

int[] b = new int[3];

for (int i = 0; i <a.length; i++) a[i] = i;

You can pass an

array of strings

to main as an

argument

Trang 31

The assignment b = a in the preceding code gives the array variable b the same

memory address as the array variable a4Pa and b are two different names for

a[2]

value of b[2]

XJUIBSSBZT*GZPVXBOUUIFBSSBZTa and b in the preceding code to be different

for (int i = 0; i < a.length; i++)

int[] a = new int[3];

int[] b = new int[3];

for (int i = 0; i < a.length; i++)

The operator == tests whether two arrays are at the same place in memory

Trang 32

LISTING 7.6 Two Kinds of Equality (part 1 of 2)

int[] a = new int[3];

int[] b = new int[3];

setArray(a);

setArray(b);

if (b == a) System.out.println("Equal by ==.");

else System.out.println("Not equal by ==.");

if (equals(b, a)) System.out.println("Equal by the equals method.");

else System.out.println("Not equal by the equals method."); }

public static boolean equals(int[] a, int[] b) {

boolean elementsMatch = true;//tentatively

if (a.length != b.length) elementsMatch = false;

else {

int i = 0;

while (elementsMatch && (i < a.length)) {

if (a[i] != b[i]) elementsMatch = false;

i++;

} }

return elementsMatch;

} public static void setArray(int[] array) {

for (int i = 0; i < array.length; i++) array[i] = i;

} }

(continued)

The arrays a and b

contain the same integers

in the same order.

Trang 33

LISTING 7.6 Two Kinds of Equality (part 2 of 2)

Screen Output

Not equal by ==.

Equal by the equals method.

GOTCHA Using the Operators = and == with Arrays

:PVDBOVTFUIFBTTJHONFOUPQFSBUPSUPHJWFBOBSSBZNPSFUIBOPOFOBNF:PV

UIFFRVBMJUZPQFSBUPSUFTUTXIFUIFSUXPBSSBZOBNFTSFGFSFODFUIFTBNFNFNPSZ

address It does not test whether two different arrays contain the same values ■

REMEMBER Array Types Are Reference Types

A variable of an array type holds only the address where the array is

stored in memory This memory address is called a reference to the array

object in memory For this reason, array types are often called reference

types Recall from Chapter 5 that a reference type is any type whose

variables hold references—that is, memory addresses—as opposed to the

actual item named by the variable Array types and class types are both

reference types Primitive types are not reference types.

FAQ Are arrays really objects?

Arrays do not belong to any class Some other features of class objects—

such as inheritance, which we will discuss in Chapter 8—do not apply to

arrays So whether arrays should be considered objects is not 100 percent

clear However, that is primarily an academic debate In Java, arrays are

officially objects Whenever Java documentation says that something

applies to all objects, it also applies to arrays.

Methods That Return Arrays

SFUVSOUZQFJOUIFTBNFXBZUIBUZPVTQFDJGZUIFUZQFPGBOBSSBZQBSBNFUFS'PS

version computes the various possible average scores within a method named

Trang 34

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter your score on exam 1:");

int firstScore = keyboard.nextInt();

int[] nextScore = new int[3];

for (int i = 0; i < nextScore.length; i++) nextScore[i] = firstScore + 5 * i;

double[] averageScore = getArrayOfAverages(firstScore, nextScore);

for (int i = 0; i < nextScore.length; i++) {

System.out.println("If your score on exam 2 is " + nextScore[i]);

System.out.println("your average will be " + averageScore[i]);

} } public static double[] getArrayOfAverages(int firstScore,

int[] nextScore) {

double[] temp = new double[nextScore.length];

for (int i = 0; i < temp.length; i++) temp[i] = getAverage(firstScore, nextScore[i]);

return temp;

} public static double getAverage(int n1, int n2) {

return (n1 + n2) / 2.0;

}

the same as in Listing 7.5.

getArrayofAverages This new method returns these average scores as an array following steps:

double temp = new double[nextScore.length];

<Fill the array temp.>

return temp;

Trang 35

RECAP Returning an Array

A method can return an array in basically the same way that it returns a

value of another type.

The method need not be static and need not be public The following are

some of the other acceptable method headings:

public Base_Type[] Method_Name(Parameter_List)

private static Base_Type[] Method_Name(Parameter_List)

private Base_Type[] Method_Name(Parameter_List)

RECAP The Name of an Array’s Data Type

The data-type name for an array is always of the form

Base_Type[]

This is true when declaring an array variable, specifying the type of an

array parameter, or specifying that a method returns an array.

EXAMPLES

int[] counter = new int[10];

Species[] ghost = new Species[20];

public static double[] halfAll(int[] arrayToBeHalved);

Trang 36

GOTCHA Privacy Leaks with Arrays

A private instance variable that has an array type can be modified outside of its

S E L F - T E S T Q U E S T I O N S

  8IBUPVUQVUXJMMCFQSPEVDFECZUIFGPMMPXJOHDPEF char[] a = new char[3];

for (int i = 0; i <a.length; i++) a[i] = a;

char[] b = a;

System.out.println("a[1] = " + a[1] + ", b[1] = " + b[1]); System.out.println("a[2] = " + a[2] + ", b[2] = " + b[2]); b[2] = b;

System.out.println("a[1] = " + a[1] + ", b[1] = " + b[1]); System.out.println("a[2] = " + a[2] + ", b[2] = " + b[2]);

 (JWFUIFEFGJOJUJPOPGBTUBUJDNFUIPEDBMMFEshowArray that has an array of base type charBTBTJOHMFQBSBNFUFSBOEUIBUXSJUFTPOFMJOFPGUFYUUPUIFscreen consisting of the characters in the array argument written in order

11 Give the definition of a static method called getArrayOfHalves that has

an array of base type double as a single parameter and that returns another CVUXIPTFFMFNFOUTIBWFFBDICFFOEJWJEFECZ

 5IFGPMMPXJOHNFUIPEDPNQJMFTBOEFYFDVUFTCVUEPFTOPUXPSLBTZPVNJHIUIPQF8IBUJTXSPOHXJUIJU

/** Doubles the size of an array */

public static void doubleSize(int[] a) {

a = new int[a.length * 2];

}

Trang 37

 4VQQPTF UIBU XF BEE UIF GPMMPXJOH NFUIPE UP UIF DMBTTSalesReporter

JO -JTUJOH  TP UIBU B QSPHSBN VTJOH UIJT DMBTT DBO BDDFTT UIF TBMFT

associates:

/** Returns an array of SalesAssociate objects */

public SalesAssociate[] getSalesTeam()

{

return team;

}

8JMMUIJTNFUIPEDPNQJMFBOEFYFDVUFBTJOEJDBUFE *TBEEJOHUIJTNFUIPE

to the class SalesReporterBHPPEJEFB

7.3 PROGRAMMING WITH ARRAYS AND CLASSES

The Moving Finger writes; and, having writ,

Moves on; nor all your Piety and Wit.

Shall lure it back to cancel half a line.

Nor all your Tears wash out a Word of it.

JOBDMBTT8FCFHJOXJUIBQSPHSBNNJOHFYBNQMFUIBUJMMVTUSBUFTTPNFCBTJD

UFDIOJRVFT

PROGRAMMING EXAMPLE A Specialized List Class

One way to use an array for a special purpose is to make the array an instance

so you can add any checks and automatic processing that you want This

allows you to define classes whose objects are something like special-purpose

class

such as a grocery list or a list of things to do The class will have the rather long

nameOneWayNoRepeatsList.1

1

Collection and List,

and it could be confusing to use these short names for something other than their usual

meaning.

Trang 38

The class OneWayNoRepeatsList will have a method for adding items

again with a blank list Each object of the class OneWayNoRepeatsList has a BOZXIFSFGSPN[FSPUPUIFNBYJNVNOVNCFSPGJUFNT

An object of the class OneWayNoRepeatsList has an array of strings as

You can use int variables to hold numbers that indicate positions in the list One of these int

getEntryAt lets you recover the item at a given position If toDoList is an object of the class OneWayNoRepeatsList

string variable next to the entry at the second position:

String next = toDoList.getEntryAt(2);

Other methods add an entry to the end of the list or erase the entire list These are the only ways that the list can be changed You cannot change or other than at the end of the list

*O$IBQUFSXFEJTDVTTFEFODBQTVMBUJPO5IFDMBTTOneWayNoRepeatsList

UPVTFUIFDMBTT4PJUNBLFTTFOTFUPUFMMZPVIPXUPVTFUIJTDMBTTCFGPSFXFgive the definition

-JTUJOHDPOUBJOTBQSPHSBNUIBUEFNPOTUSBUFTIPXUPVTFTPNFPGUIFmethods for the class OneWayNoRepeatsList Notice that the constructor takes BO JOUFHFS BSHVNFOU 5IJT JOUFHFS TQFDJGJFT UIF NBYJNVN OVNCFS PG FOUSJFTthat can be placed on the list The number is small for our demonstration.The method addItem

following adds the string named by the variable next to the end of the list toDoList:toDoList.addItem(next);

int position = toDoList.START_POSITION;

Trang 39

LISTING 7.8 Using the Class OneWayNoRepeatsList (part 1 of 2)

import java.util.Scanner;

public class ListDemo

{

public static final int MAX_SIZE = 3; //Assumed > 0

public static void main(String[] args)

{

OneWayNoRepeatsList toDoList =

new OneWayNoRepeatsList(MAX_SIZE);

System.out.println(

"Enter items for the list, when prompted.");

boolean moreEntries = true;

String next = null;

Scanner keyboard = new Scanner(System.in);

while (moreEntries && !toDoList.isFull())

System.out.print("More items for the list? ");

String ans = keyboard.nextLine();

if (ans.trim().equalsIgnoreCase("no"))

moreEntries = false; //User says no more

}

}

System.out.println("The list contains:");

int position = toDoList.START_POSITION;

Trang 40

null signals the

list’s end

Sample Screen Output

Enter items for the list, when prompted.

Enter an item:

Buy milk More items for the list? yes Enter an item:

Walk dog More items for the list? yes Enter an item:

Buy milk More items for the list? yes Enter an item:

Write program The list is now full.

The list contains:

Buy milk Walk dog Write program

The named constant toDoList.START_POSITION is simply another name for the number 1.You can invoke the method getEntryAt to retrieve the item at nextFRVBMUPUIFTUSJOHBUUIFQPTJUJPOHJWFOCZUIFWBSJBCMFposition:

next = toDoList.getEntryAt(position);

ofpositionthrough the list:

int position = toDoList.START_POSITION;

Ngày đăng: 09/01/2023, 02:56

TỪ KHÓA LIÊN QUAN