PROGRAMMING WITH ARRAYS AND CLASSES

Một phần của tài liệu java an introductioan to problem solving and programming 6th edition (Trang 551 - 561)

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.

—OMAR KHAYYAM,THE RUBA’IYAT '*5;(&3"-%53"/4-"5*0/

*O UIJT TFDUJPO XF QSFTFOU TPNF BEEJUJPOBM UFDIOJRVFT GPS XPSLJOH XJUI BSSBZT*OQBSUJDVMBSXFEJTDVTTVTJOHBOBSSBZWBSJBCMFBTBOJOTUBODFWBSJBCMF 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 WBSJBCMFPGBDMBTT5IFBSSBZJTBDDFTTFEPOMZUISPVHIUIFDMBTTNFUIPETBOE 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 BSSBZT *O UIJT QSPHSBNNJOH FYBNQMF XF QSFTFOU BO FYBNQMF PG POF TVDI class.

8FXJMMEFGJOFBDMBTTXIPTFPCKFDUTDBOCFVTFEGPSLFFQJOHMJTUTPGJUFNT such as a grocery list or a list of things to do. The class will have the rather long nameOneWayNoRepeatsList.1

1-POHOBNFTBSFUSBEJUJPOBMJO+BWBCVUXFEJEOPUDIPPTFBMPOHOBNFKVTUUPCFUSB- EJUJPOBM"MMUIFTIPSUOBNFTMJLFCollection and List,BMSFBEZIBWFBNFBOJOHJO+BWB and it could be confusing to use these short names for something other than their usual meaning.

516 CHAPTER 7 / Arrays

The class OneWayNoRepeatsList will have a method for adding items UP UIF MJTU "O JUFN PO UIF MJTU JT B TUSJOH XIJDI JO BO BQQMJDBUJPO XPVME TBZ XIBUFWFS ZPV XBOU UIF JUFN UP TBZ TVDI BT i#VZ NJMLw 5IJT DMBTT IBT OP NFUIPE UP DIBOHF B TJOHMF JUFN PS EFMFUF BO JUFN GSPN UIF MJTU *U EPFT IPXFWFS IBWF B NFUIPE UIBU MFUT ZPV FSBTF UIF FOUJSF MJTU BOE TUBSU PWFS again with a blank list. Each object of the class OneWayNoRepeatsList has a NBYJNVN OVNCFS PG JUFNT JU DBO IPME "U BOZ UJNF UIF MJTU NJHIU DPOUBJO BOZXIFSFGSPN[FSPUPUIFNBYJNVNOVNCFSPGJUFNT

An object of the class OneWayNoRepeatsList has an array of strings as BOJOTUBODFWBSJBCMF5IJTBSSBZIPMETUIFJUFNTPOUIFMJTU)PXFWFSZPVEP OPUBDDFTTUIFBSSBZEJSFDUMZ*OTUFBEZPVVTFBDDFTTPSBOENVUBUPSNFUIPET You can use int variables to hold numbers that indicate positions in the list.

One of these int WBSJBCMFT JT UIF TBNF UIJOH BT BO JOEFY CVU UIF QPTJUJPOT BSF OVNCFSFE TUBSUJOH XJUI SBUIFS UIBO 'PS FYBNQMF B NFUIPE OBNFE getEntryAt lets you recover the item at a given position. If toDoList is an object of the class OneWayNoRepeatsList UIF GPMMPXJOH TUBUFNFOU TFUT UIF 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 EFMFUF B QBSUJDVMBS FOUSZ PO UIF MJTU BOE ZPV DBOOPU BEE BO FOUSZ BOZXIFSF other than at the end of the list.

*O$IBQUFSXFEJTDVTTFEFODBQTVMBUJPO5IFDMBTTOneWayNoRepeatsList JTBHPPEFYBNQMFPGBXFMMFODBQTVMBUFEDMBTTTJODFJUIJEFTJUTEFUBJMTGSPN UIFQSPHSBNNFSXIPVTFTJU#VUDMFBSMZUIFQSPHSBNNFSOFFETUPLOPXIPX UPVTFUIFDMBTT4PJUNBLFTTFOTFUPUFMMZPVIPXUPVTFUIJTDMBTTCFGPSFXF give the definition.

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

The method addItem BEET B TUSJOH UP UIF FOE PG UIF MJTU 'PS FYBNQMF UIF following adds the string named by the variable next to the end of the list toDoList:

toDoList.addItem(next);

*GZPVMPPLBUUIFTBNQMFPVUQVUJO-JTUJOHZPVXJMMTFFUIBUBuy milk JTBEEFEUPUIFMJTUUXJDFCVUUIBUJUBQQFBSTPOUIFMJTUPOMZPODF*GUIFJUFN CFJOHBEEFEJTBMSFBEZPOUIFMJTUUIFNFUIPEaddItem has no effect. That way the list has no repeats.

You can use an int variable to step through the list from beginning UP FOE 5IF UFDIOJRVF JT JMMVTUSBUFE BU UIF FOE PG -JTUJOH :PV CFHJO CZ initializing an intWBSJBCMFUPUIFGJSTUQPTJUJPOPOUIFMJTUBTGPMMPXT

int position = toDoList.START_POSITION;

A class of lists of strings

An array of strings as an instance variable

Access to the strings in a list is only via methods

Stepping through a list

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.println("Enter an item:");

next = keyboard.nextLine();

toDoList.addItem(next);

if (toDoList.isFull()) {

System.out.println("List is now full.");

} else {

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;

next = toDoList.getEntryAt(position);

while (next != null) //null indicates end of list {

System.out.println(next);

position++;

next = toDoList.getEntryAt(position);

} } }

(continued)

518 CHAPTER 7 / Arrays

null signals the list’s end

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

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 CVUXFVTFJUCFDBVTFXFBSFUIJOLJOHPGUIJTBTUIFTUBSUPGUIFMJTUOPUBT the number 1.You can invoke the method getEntryAt to retrieve the item at BHJWFOQPTJUJPOJOUIFMJTU'PSFYBNQMFUIFGPMMPXJOHTFUTUIFTUSJOHWBSJBCMF nextFRVBMUPUIFTUSJOHBUUIFQPTJUJPOHJWFOCZUIFWBSJBCMFposition:

next = toDoList.getEntryAt(position);

5PPCUBJOUIFOFYUJUFNPOUIFMJTUUIFQSPHSBNTJNQMZJODSFNFOUTUIFWBMVF ofposition5IFGPMMPXJOHDPEFUBLFOGSPN-JTUJOHJMMVTUSBUFTTUFQQJOH through the list:

int position = toDoList.START_POSITION;

next = toDoList.getEntryAt(position);

while (next != null) {

System.out.println(next);

position++;

next = toDoList.getEntryAt(position);

}

Once the value of position is incremented beyond the last position in UIF MJTU OP FOUSZ XJMM CF BU QPTJUJPO 4P XF OFFE TPNF XBZ UP DPOWFOJFOUMZ

JOEJDBUFUIBUUIFFOEPGUIFMJTUIBTCFFOSFBDIFE0UIFSXJTFXFNJHIUBDDFTT TPNFiHBSCBHFwWBMVFJOUIFVOVTFEQPSUJPOPGUIFBSSBZ5PUBLFDBSFPGUIJT QSPCMFN XF XJMM NBLFgetEntryAt return the value null when there is no entry at the given position. Note that null JT EJGGFSFOU GSPN BOZ SFBM TUSJOH BOETPJUXJMMOPUBQQFBSPOBOZMJTU5IVTZPVSQSPHSBNDBOUFTUGPSUIFFOE of the list by checking for the value null 3FDBMM UIBU UP UFTU GPS FRVBMJUZ PS JOFRVBMJUZXJUInullZPVVTF== or !=; you do not use an equals method.

The complete definition of the class OneWayNoRepeatsList is given in -JTUJOH 5IF FOUSJFT PO B MJTU BSF LFQU JO UIF JOTUBODF WBSJBCMFentry which is an array of base type String 5IVT UIF NBYJNVN OVNCFS PG entries that the list can hold is entry.length )PXFWFS UIF MJTU OPSNBMMZ XJMM OPU CF GVMM BOE TP XJMM DPOUBJO GFXFS UIBOentry.length entries. To keep track of how much of the array entry JT DVSSFOUMZ VTFE UIF DMBTT IBT an instance variable called countOfEntries. The entries themselves are kept JO UIF JOEFYFE WBSJBCMFTentry[0]entry[1]entry[2] BOE TP PO UISPVHI entry[countOfEntries — 1]. The values of the elements whose indices are countOfEntries or higher are just garbage values and do not represent entries PO UIF MJTU 5IVT XIFO ZPV XBOU UP TUFQ UISPVHI UIF JUFNT PO UIF MJTU ZPV stop after entry[countOfEntries — 1].

'PSFYBNQMFUIFEFGJOJUJPOPGUIFNFUIPEisOnList has a while loop that TUFQTUISPVHIUIFBSSBZDIFDLJOHUPTFFXIFUIFSUIFBSHVNFOUJTFRVBMUPBOZ of the entries on the list:

while ((!found) && (i <countOfEntries)) {

if (item.equalsIgnoreCase(entry[i])) found = true;

else i++;

}

The code checks only array elements whose indices are less than countOfEntries.

*UEPFTOPUDIFDLUIFSFTUPGUIFBSSBZCFDBVTFUIPTFBSSBZFOUSJFTBSFOPUPO the list.

The complete class OneWayNoRepeatsList has a few more methods UIBOUIPTFXFVTFEJOUIFEFNPOTUSBUJPOQSPHSBNJO-JTUJOH5IFTFFYUSB methods make the class more useful for a wider variety of applications.

Note that although the array entry IBT JOEJDFT TUBSUJOH XJUI JG XF use an int variable as a position marker—such as the variable position in -JTUJOH‰UIFOVNCFSJOHTUBSUTBUOPU5IFDMBTTNFUIPETBVUPNBUJDBMMZ BEKVTU UIF JOEJDFT TP XIFO ZPV XBOU UIF JUFN BU MPDBUJPOposition ZPV get entry[position — 1] 8F DPVME PG DPVSTF IBWF DPNQFOTBUFE GPS UIF EJGGFSFODF CFUXFFO BSSBZ JOEJDFT BOE MJTU QPTJUJPOT CZ BMMPDBUJOH BO FYUSB element in the array entry and ignoring entry[0] BT XF TVHHFTUFE FBSMJFS OFBSUIFFOEPGUIFTFDUJPOFOUJUMFEi.PSF"CPVU"SSBZ*OEJDFTw&YFSDJTFBU the end of the previous section asks you to do just that.

Garbage values occur after the last entry in the list

The loop in the method isOnList

Positions of entries on a list begin at 1, but in an array, they begin at 0

520 CHAPTER 7 / Arrays

LISTING 7.9 An Array Wrapped in a Class to Represent a List (part 1 of 3)

/**

An object of this class is a special kind of list of strings.

You can write the list only from beginning to end. You can add only to the end of the list. You cannot change individual en- tries, but you can erase the entire list and start over. No entry may appear more than once on the list. You can use int variables as position markers into the list. Position markers are similar to array indices, but are numbered starting with 1.

*/

public class OneWayNoRepeatsList {

public static int START_POSITION = 1;

public static int DEFAULT_SIZE = 50;

//entry.length is the total number of items you have room //for on the list (its capacity); countOfEntries is the number of //items currently on the list.

private int countOfEntries; //can be less than entry.length.

private String[] entry;

/**

Creates an empty list with a given capacity.

*/

public OneWayNoRepeatsList(int maximumNumberOfEntries) {

entry = new String[maximumNumberOfEntries];

countOfEntries = 0;

} /**

Creates an empty list with a capacity of DEFAULT_SIZE.

*/

public OneWayNoRepeatsList() {

entry = new String[DEFAULT_SIZE];

countOfEntries = 0;

// or replace these two statements with this(DEFAULT_SIZE);

}

public boolean isFull() {

return countOfEntries == entry.length;

}

public boolean isEmpty() {

return countOfEntries == 0;

}

(continued)

LISTING 7.9 An Array Wrapped in a Class to Represent a List (part 2 of 3)

/**

Precondition: List is not full.

Postcondition: If item was not on the list, it has been added to the list.

*/

public void addItem(String item) {

if (!isOnList(item)) {

if (countOfEntries == entry.length) {

System.out.println("Adding to a full list!");

System.exit(0);

} else {

entry[countOfEntries] = item;

countOfEntries++;

}

} //else do nothing. Item is already on the list.

} /**

If the argument indicates a position on the list, the entry at that specified position is returned;

otherwise, null is returned.

*/

public String getEntryAt(int position) {

String result = null;

if ((1 <= position) && (position <= countOfEntries)) result = entry[position - 1];

return result;

} /**

Returns true if position indicates the last item on the list; otherwise, returns false.

*/

public boolean atLastEntry(int position) {

return position == countOfEntries;

}

(continued)

522 CHAPTER 7 / Arrays

LISTING 7.9 An Array Wrapped in a Class to Represent a List (part 3 of 3)

/**

Returns true if item is on the list;

otherwise, returns false. Does not differentiate between uppercase and lowercase letters.

*/

public boolean isOnList(String item) {

boolean found = false;

int i = 0;

while (!found && (i < countOfEntries)) {

if (item.equalsIgnoreCase(entry[i])) found = true;

else i++;

}

return found;

}

public int getMaximumNumberOfEntries() {

return entry.length;

}

public int getNumberOfEntries() {

return countOfEntries;

}

public void eraseList() {

countOfEntries = 0;

} }

Note that the class OneWayNoRepeatsList provides three ways to detect UIFFOEPGBMJTUBTTVNJOHZPVVTFBOint variable position to access entries in the list:

t *GpositionFRVBMTgetNumberOfEntries()position is at the last entry.

t *GatLastEntry(position) returns trueposition is at the last entry.

t *GgetEntryAt(position) returns nullposition is beyond the last entry.

8F FOE UIJT QSPHSBNNJOH FYBNQMF XJUI B NFOUJPO UIBU UIF +BWB $MBTT Library contains the class ArrayList that you can use to create lists that are Ways to detect

the end of a list

NPSFHFOFSBMBOEGMFYJCMFUIBOUIFMJTUXFVTFEIFSF-JLFPVSDMBTTArrayList VTFTBOBSSBZUPSFQSFTFOUUIFMJTU$IBQUFSXJMMJOUSPEVDFZPVUPUIJTDMBTT CVUJGZPVMJLFZPVDBOTLJQBIFBEBOESFBEBCPVUJUOPX

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

3FQMBDFUIFMBTUMPPQJO-JTUJOHXJUIBfor loop that uses the number of entries in the list.

3FQMBDF UIF MBTU MPPQ JO -JTUJOH XJUI B MPPQ UIBU VTFT UIF NFUIPE atLastEntry.

Partially Filled Arrays

The array entry in the class OneWayNoRepeatsList JO -JTUJOH DPOUBJOT UIF FOUSJFT PO B MJTU 8IFO UIF MJTU JT OPU ZFU GVMMentry is a partially filled array. *O TPNF TJUVBUJPOT TVDI BT UIJT POF XF OFFE TPNF CVU OPU BMM PG UIF JOEFYFE WBSJBCMFT JO BO BSSBZ *O UIFTF DBTFT XF NVTU LFFQ USBDL PG how much of the array has been used so that we know how much of it is BWBJMBCMF/PSNBMMZXFDBOVTFBOJOUWBSJBCMFUPDPVOUUIFJUFNTJOUIFBSSBZ 'PSFYBNQMFUIFDMBTTOneWayNoRepeatsListJO-JTUJOHVTFTUIFJOTUBODF variable countOfEntries GPS UIJT QVSQPTF *O QBSUJDVMBScountOfEntries JNQMJFTUIBUUIFMJTUDPOUBJOTUIFBSSBZFMFNFOUTXIPTFJOEJDFTBSFUISPVHI countOfEntries — 1BT'JHVSFJMMVTUSBUFT*UJTWFSZJNQPSUBOUUPLFFQUSBDLPG IPXNVDIPGUIFBSSBZJTDVSSFOUMZCFJOHVTFECFDBVTFUIFPUIFSBSSBZFOUSJFT DPOUBJOJSSFMFWBOUWBMVFT8IFOBDDFTTJOHBQBSUJBMMZGJMMFEBSSBZZPVXBOUUP access only those elements in the array that contain meaningful values. You XBOU UP JHOPSF UIF SFTU PG UIF BSSBZ 0G DPVSTF BT ZPV BEE PS EFMFUF FOUSJFT GSPN B QBSUJBMMZ GJMMFE BSSBZ UIF CPSEFSMJOF CFUXFFO NFBOJOHGVM WBMVFT BOE

An array can have fewer meaningful entries than its capacity

FIGURE 7.4 A Partially Filled Array

entry

Unused elements

entry.length has a value of 5.

countOfEntries has a value of 3.

Buy milk.

Call home.

Go to beach.

?

? entry[0]

entry[1]

entry[2]

entry[3]

entry[4]

The item at index countOfEntries – 1

The arrayentry, as used in an object of the class OneWayNoRepeatsList with a maximum capacity of 5 entries

524 CHAPTER 7 / Arrays

JSSFMFWBOUWBMVFTDBONPWFBOEUIJTNPWFNFOUNVTUCFSFDPSEFECZDIBOHJOH the value of a suitable intWBSJBCMFTVDIBTcountOfEntries.

5ZQJDBMMZUIFNFBOJOHGVMQBSUPGBOBSSBZCFHJOTBUUIFCFHJOOJOHPGUIF BSSBZCVUUIJTJTOPUBOBCTPMVUFSFRVJSFNFOU8IFOZPVXBOUUPDPOTJEFSB QPSUJPOPGBOBSSBZUIBUEPFTOPUCFHJOBUUIFJOEFYZPVDBOEFGJOFUXPint variables—such as first and last—to record the indices of the first and last FMFNFOUT SFTQFDUJWFMZ PG UIF SBOHF PG FMFNFOUT UIBU ZPV XBOU UP DPOTJEFS These variables might be either instance variables or parameters to a method.

'PSFYBNQMFXFDPVMEEFGJOFBTUBUJDNFUIPEIBWJOHUIFGPMMPXJOHIFBEJOH /** Precondition: 0 <= first <= last < anArray.length */

public static void processArray(double[] anArray, int first, int last)

REMEMBER The Number of Entries in an Array vs. the Array’s Length

Distinguish between the number of entries that you use in an array and the array’s capacity. The capacity of an array a is a.length. This is the number of array elements that are created for you when you define the array. You might not use all of these elements. In this case, you need to keep track of how many you have used. Typically, you will have two integers: One is the capacity of the array, and one is the number of elements you have used.

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

4VQQPTFa is an array of values of type double. Write some code to display all the elements in aPOUIFTDSFFOPOFFMFNFOUQFSMJOF

4VQQPTFa is an array of values of type double that is partially filled. The array contains meaningful values in only the first numberUsedFMFNFOUT wherenumberUsed is a variable of type int. Write some code to display all the meaningful values in the array a.

*G UIF BSSBZa JO UIF QSFWJPVT RVFTUJPO IBT SPPN GPS UFO FMFNFOUT CVU DPOUBJOT POMZ UISFF FMFNFOUT XIBU JOEFYFE WBSJBCMFT XJMM DPOUBJO UIF UISFFFMFNFOUT 8IBUJTUIFWBMVFPGnumberUsed?

$POTJEFS UIF QBSUJBMMZ GJMMFE BSSBZa GSPN 4FMG5FTU 2VFTUJPO 8SJUF TPNF DPEF UIBU XJMM QMBDF UIF OVNCFS SJHIU BGUFS UIF MBTU OVNCFS currently in a. You can assume that the array aJTOPUGVMM Hint: You must updatenumberUsed

Một phần của tài liệu java an introductioan to problem solving and programming 6th edition (Trang 551 - 561)

Tải bản đầy đủ (PDF)

(987 trang)