Ebook Java: Giới thiệu về lập trình và giải quyết vấn đề với mảng

Tài liệu nghiên cứu Ebook java an introduction to problem solving programming sixth edition part 2, tổng hợp lý thuyết và thực hành, cung cấp kiến thức chuyên sâu về .

Trường đại học

Trường Đại Học

Chuyên ngành

Lập Trình Java

Người đăng

Ẩn danh

Thể loại

bài luận

2023

473
1
0

Phí lưu trữ

75 Point

Mục lục chi tiết

4. CHƯƠNG 4: SORTING AND SEARCHING ARRAYS

4.1. Creating and Accessing Arrays

4.2. Selection Sort

4.3. Array Details

4.4. Other Sorting Algorithms

4.5. The Instance Variable length

4.6. Searching an Array

4.7. More About Array Indices

4.8. Initializing Arrays

4.9. Multidimensional Arrays

4.9.1. Multidimensional-Array Basics

4.9.2. Multidimensional-Array Parameters and Returned Values

4.10. Arrays in Classes and Methods

4.10.1. Case Study: Sales Report

4.10.2. Java’s Representation of Multidimensional Arrays as Method Arguments

4.10.3. Entire Arrays as Arguments to a Method

4.10.4. Ragged Arrays (Optional)

4.11. Programming Example: Employee Time Records

4.12. Methods That Return Arrays

4.13. Text Areas and Text Fields

4.13.1. Programming Example: A Question-and-Answer Applet

4.13.2. Programming Example: A Specialized List Class

4.13.3. The Classes JTextArea and JTextField

4.14. Drawing Polygons

4.15. Chapter Summary

4.16. Programming Projects

4.17. Answers to Self-Test Questions

Trích đoạn nội dung tài liệu

4 SORTING AND SEARCHING ARRAYS 525 Creating and Accessing Arrays 482 Selection Sort 525 Array Details 485 Other Sorting Algorithms 529 The Instance Variable length 488 Searching an Array 531 More About Array Indices 491 Initializing Arrays 494 7.5 MULTIDIMENSIONAL ARRAYS 532 Multidimensional-Array Basics 533 7.2 ARRAYS IN CLASSES Multidimensional-Array Parameters and Returned AND METHODS 495 Values 536 Case Study: Sales Report 495 Java’s Representation of Multidimensional Indexed Variables as Method Arguments 503 Arrays 539 Entire Arrays as Arguments to a Method 505 Ragged Arrays (Optional ) 540 Arguments for the Method main 507 Programming Example: Employee Time Array Assignment and Equality 508 Records 542 Methods That Return Arrays 511 7.3 PROGRAMMING WITH ARRAYS Text Areas and Text Fields 548 AND CLASSES 515 Programming Example: A Question-and-Answer Programming Example: A Specialized List Class 515 Applet 548 Partially Filled Arrays 523 The Classes JTextArea and JTextField 551 Drawing Polygons 553 Chapter Summary 556 Programming Projects 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.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.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 BOJDF DPNQBDUXBZ data type 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] Variables like temperature[0] and temperature[1] that have an integer An index is an integer FYQSFTTJPO JO TRVBSF CSBDLFUT BSF DBMMFE indexed variables, subscripted expression that variable, array elements, or simply elements.5IFJOUFHFSFYQSFTTJPOXJUIJO indicates an array UIFTRVBSFCSBDLFUTJTDBMMFEBOindex or a subscript. Note that the numbering element 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.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.println("Enter day number (0 - 6):"); int index = keyboard.1 Array Basics 483 FIGURE 7.1 A Common Way to Visualize an Array Indices 0 1 2 3 4 5 6 32 30 25.5 29 The array temperature temperature[5] 4JODFBOJOEFYDBOCFBOFYQSFTTJPO XFDBOXSJUFBMPPQUPSFBEWBMVFTJOUP the array temperature BTGPMMPXT System.nextDouble(); 5IFVTFSDPVMEUZQFUIFTFWFOWBMVFTPOTFQBSBUFMJOFTPSBMMPOPOFMJOF TFQBSBUFE CZTQBDFT"GUFSUIFBSSBZWBMVFTBSFSFBEJO XFDBOEJTQMBZUIFNBTGPMMPXT System.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.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.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.println("Enter 7 temperatures:"); double sum = 0; for (int index = 0; index < 7; index++) (continued) 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.println("The average temperature is " + average); // Display each temperature and its relation to the average: System.println(temperature[index] + " above average"); else //temperature[index] == average System.println("Have a nice week."); } } Sample Screen Output Enter 7 temperatures: 32 30 25.5 29 The average temperature is 29.7428 The temperatures are 32.0 below average Have a nice week.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 elements is called the base square brackets after the variable instead type of the array. In this of after the base type, as in the following FYBNQMF UIFCBTFUZQFJT int. example: 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 The number of variables pressure[0]through pressure[99]. Note that because the indices elements in an TUBSU BU   BO BSSBZ PG MFOHUI   TVDI BT pressure  XJMM IBWF no JOEFYFE array is its length 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 The type of the elements are SpeciesPCKFDUT XIFSFSpecies is a class: array elements is the array’s base Species[] entry = new Species[3]; type 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) 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 inte- HFST 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.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 public static final int NUMBER_OF_READINGS = 100; constant when int[] pressure = new int[NUMBER_OF_READINGS]; defining an array +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 temperature[n + 2] called an array element, an element, or a subscripted variable) temperature[n + 2] Value of the indexed variable (also called an element of the array) temperature[n + 2] = 32; System.println("How many temperatures do you have?"); int size = keyboard.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. 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.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 Species[] entry = new Species[20]; length of e.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. 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.

Nội dung được bảo vệ bản quyền — Tải xuống đầy đủ