Kĩ thuật lập trình - Arrays
Command-line arguments
Pass arguments from the command line
String args[]
Appear after the class name in the java command
java MyClass a b
Number of arguments passed in from command line
args.length
First command-line argument
args[ 0 ]
100 trang |
Chia sẻ: huyhoang44 | Lượt xem: 717 | Lượt tải: 0
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Arrays, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
7Arrays1Now go, write it before them in a table, and note it in a book.Isaiah 30:8To go beyond is as wrong as to fall short. ConfuciusBegin at the beginning, and go on till you come to the end: then stop.Lewis Carroll 2OBJECTIVESIn this chapter you will learn: What arrays are.To use arrays to store data in and retrieve data from lists and tables of values. To declare an array, initialize an array and refer to individual elements of an array.To use the enhanced for statement to iterate through arrays.To pass arrays to methods.To declare and manipulate multidimensional arrays.To write methods that use variable-length argument lists.To read command-line arguments into a program.37.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 Case Study: Card Shuffling and Dealing Simulation 7.6 Enhanced for Statement 7.7 Passing Arrays to Methods 7.8 Case Study: Class GradeBook Using an Array to Store Grades 7.9 Multidimensional Arrays 7.10 Case Study: Class GradeBook Using a Two-Dimensional Array 7.11 Variable-Length Argument Lists 7.12 Using Command-Line Arguments 7.13 (Optional) GUI and Graphics Case Study: Drawing Arcs 7.14 (Optional) Software Engineering Case Study: Collaboration Among Objects7.15 Wrap-Up 47.1 IntroductionArraysData structuresRelated data items of same typeRemain same size once createdFixed-length entries57.2 ArraysArrayGroup of variablesHave same typeReference type6Fig. 7.1 | A 12-element array. 77.2 Arrays (Cont.)IndexAlso called subscriptPosition number in square bracketsMust be positive integer or integer expressionFirst element has index zero a = 5; b = 6; c[ a + b ] += 2;Adds 2 to c[ 11 ]8Common Programming Error 7.1Using a value of type long as an array index results in a compilation error. An index must be an int value or a value of a type that can be promoted to int—namely, byte, short or char, but not long.97.2 Arrays (Cont.)Examine array cc is the array namec.length accesses array c’s lengthc has 12 elements ( c[0], c[1], c[11] )The value of c[0] is –45107.3 Declaring and Creating ArraysDeclaring and Creating arraysArrays are objects that occupy memoryCreated dynamically with keyword new int c[] = new int[ 12 ];Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create arrayWe can create arrays of objects tooString b[] = new String[ 100 ];11Common Programming Error 7.2In an array declaration, specifying the number of elements in the square brackets of the declaration (e.g., int c[ 12 ];) is a syntax error. 12Good Programming Practice 7.1For readability, declare only one variable per declaration. Keep each declaration on a separate line, and include a comment describing the variable being declared.13Common Programming Error 7.3Declaring multiple array variables in a single declaration can lead to subtle errors. Consider the declaration int[] a, b, c;. If a, b and c should be declared as array variables, then this declaration is correct—placing square brackets directly following the type indicates that all the identifiers in the declaration are array variables. However, if only a is intended to be an array variable, and b and c are intended to be individual int variables, then this declaration is incorrect—the declaration int a[], b, c; would achieve the desired result.147.4 Examples Using ArraysDeclaring arraysCreating arraysInitializing arraysManipulating array elements157.4 Examples Using ArraysCreating and initializing an arrayDeclare arrayCreate arrayInitialize array elements16OutlineInitArray.javaLine 8Declare array as an array of intsLine 10Create 10 ints for array; each int is initialized to 0 by defaultLine 15array.length returns length of arrayLine 16array[counter] returns int associated with index in arrayProgram outputDeclare array as an array of intsCreate 10 ints for array; each int is initialized to 0 by defaultarray.length returns length of arrayarray[counter] returns int associated with index in arrayEach int is initialized to 0 by default177.4 Examples Using Arrays (Cont.)Using an array initializerUse initializer listItems enclosed in braces ({})Items in list separated by commas int n[] = { 10, 20, 30, 40, 50 };Creates a five-element arrayIndex values of 0, 1, 2, 3, 4Do not need keyword new18OutlineInitArray.javaLine 9Declare array as an array of intsLine 9Compiler uses initializer list to allocate arrayProgram outputDeclare array as an array of intsCompiler uses initializer list to allocate array197.4 Examples Using Arrays (Cont.)Calculating a value to store in each array elementInitialize elements of 10-element array to even integers20OutlineInitArray.javaLine 8Declare constant variableLine 9 Declare and create array that contains 10 intsLine 13Use array index to assign arrayProgram outputDeclare constant variable ARRAY_LENGTH using the final modifierDeclare and create array that contains 10 intsUse array index to assign array value21Good Programming Practice 7.2Constant variables also are called named constants or read-only variables. Such variables often make programs more readable than programs that use literal values (e.g., 10)—a named constant such as ARRAY_LENGTH clearly indicates its purpose, whereas a literal value could have different meanings based on the context in which it is used.22Common Programming Error 7.4Assigning a value to a constant after the variable has been initialized is a compilation error.23Common Programming Error 7.5Attempting to use a constant before it is initialized is a compilation error.247.4 Examples Using Arrays (Cont.)Summing the elements of an arrayArray elements can represent a series of valuesWe can sum these values25OutlineSumArray.javaLine 8Declare array with initializer list Lines 12-13Sum all array valuesProgram outputDeclare array with initializer list Sum all array values267.4 Examples Using Arrays (Cont.)Using bar charts to display array data graphicallyPresent data in graphical mannerE.g., bar chartExamine the distribution of grades27OutlineBarChart.java(1 of 2)Line 8Declare array with initializer list Line 19 Use the 0 flag to display one-digit grade with a leading 0Lines 23-24For each array element, print associated number of asterisksDeclare array with initializer list For each array element, print associated number of asterisks Use the 0 flag to display one-digit grade with a leading 0 28OutlineBarChart.java(2 of 2)Program output297.4 Examples Using Arrays (Cont.)Using the elements of an array as countersUse a series of counter variables to summarize data30OutlineRollDie.javaLine 10Declare frequency as array of 7 ints Lines 13-14Generate 6000 random integers in range 1-6Line 14Increment frequency values at index associated with random numberProgram outputDeclare frequency as array of 7 intsGenerate 6000 random integers in range 1-6Increment frequency values at index associated with random number317.4 Examples Using Arrays (Cont.)Using arrays to analyze survey results40 students rate the quality of food1-10 Rating scale: 1 means awful, 10 means excellentPlace 40 responses in array of integersSummarize results32OutlineStudentPoll.java(1 of 2)Lines 9-11Declare responses as array to store 40 responses Line 12Declare frequency as array of 11 int and ignore the first elementLines 16-17For each response, increment frequency values at index associated with that responseDeclare responses as array to store 40 responsesDeclare frequency as array of 11 int and ignore the first elementFor each response, increment frequency values at index associated with that response33OutlineStudentPoll.java(2 of 2)Program output34Error-Prevention Tip 7.1An exception indicates that an error has occurred in a program. A programmer often can write code to recover from an exception and continue program execution, rather than abnormally terminating the program. When a program attempts to access an element outside the array bounds, an ArrayIndexOutOfBoundsException occurs. Exception handling is discussed in Chapter 13.35Error-Prevention Tip 7.2When writing code to loop through an array, ensure that the array index is always greater than or equal to 0 and less than the length of the array. The loop-continuation condition should prevent the accessing of elements outside this range.367.5 Case Study: Card Shuffling and Dealing SimulationProgram simulates card shuffling and dealingUse random number generationUse an array of reference type elements to represent cardsThree classesCardRepresents a playing cardDeckOfCardsRepresents a deck of 52 playing cardsDeckOfCardsTestDemonstrates card shuffling and dealing37OutlineCard.javaLines 17-20Return the string representation of a card38OutlineDeckOfCards.java(1 of 2)Line 7Line 9Lines 15-16Line 17Lines 24-26Declare deck as array to store Card objectsConstant NUMBER_OF_CARDS indicates the number of Cards in the deckDeclare and initialize faces with Strings that represent the face of cardDeclare and initialize suits with Strings that represent the suit of cardFill the deck array with Cards39OutlineDeckOfCards.java(2 of 2)Lines 42-44Line 52Swap current Card with randomly selected CardDetermine whether deck is empty40OutlineDeckOfCardsTest.java(1 of 2)41OutlineDeckOfCardsTest.java(2 of 2)427.6 Enhanced for StatementEnhanced for statementIterates through elements of an array or a collection without using a counterSyntaxfor ( parameter : arrayName )statement43OutlineEnhancedForTest.javaFor each iteration, assign the next element of array to int variable number, then add it to total447.6 Enhanced for Statement (Cont.)Lines 12-13 are equivalent tofor ( int counter = 0; counter < array.length; counter++ ) total += array[ counter ];UsageCan access array elementsCannot modify array elementsCannot access the counter indicating the index 457.7 Passing Arrays to MethodsTo pass array argument to a methodSpecify array name without bracketsArray hourlyTemperatures is declared as int hourlyTemperatures = new int[ 24 ];The method call modifyArray( hourlyTemperatures );Passes array hourlyTemperatures to method modifyArray46OutlinePassArray.java(1 of 2)Line 9Line 19Declare 5-int array with initializer list Pass entire array to method modifyArray 47OutlinePassArray.java(2 of 2)Line 30Lines 36-40Lines 43-48Program outputPass array element array[3] to method modifyElement Method modifyArray manipulates the array directlyMethod modifyElement manipulates a primitive’s copy487.7 Passing Arrays to Methods (Cont.)Notes on passing arguments to methodsTwo ways to pass arguments to methodsPass-by-valueCopy of argument’s value is passed to called methodEvery primitive type is passed-by-valuePass-by-referenceCaller gives called method direct access to caller’s dataCalled method can manipulate this dataImproved performance over pass-by-valueEvery object is passed-by-referenceArrays are objectsTherefore, arrays are passed by reference49Performance Tip 7.1Passing arrays by reference makes sense for performance reasons. If arrays were passed by value, a copy of each element would be passed. For large, frequently passed arrays, this would waste time and consume considerable storage for the copies of the arrays. 507.8 Case Study: Class GradeBook Using an Array to Store GradesFurther evolve class GradeBookClass GradeBookRepresents a grade book that stores and analyzes gradesDoes not maintain individual grade valuesRepeat calculations require reentering the same gradesCan be solved by storing grades in an array51OutlineGradeBook.java(1 of 5)Line 7Line 13Declare array grades to store individual grades Assign the array’s reference to instance variable grades 52OutlineGradeBook.java(2 of 5)53OutlineGradeBook.java(3 of 5)Lines 59-64Lines 75-80Loop through grades to find the lowest grade Loop through grades to find the highest grade 54OutlineGradeBook.java(4 of 5)Lines 91-92Lines 107-108Loop through grades to sum grades for one student Loop through grades to calculate frequency 55OutlineGradeBook.java(5 of 5)Lines 134-136Loop through grades to display each grade 56Software Engineering Observation 7.1A test harness (or test application) is responsible for creating an object of the class being tested and providing it with data. This data could come from any of several sources. Test data can be placed directly into an array with an array initializer, it can come from the user at the keyboard, it can come from a file (as you will see in Chapter 14), or it can come from a network (as you will see in Chapter 24). After passing this data to the class's constructor to instantiate the object, the test harness should call upon the object to test its methods and manipulate its data. Gathering data in the test harness like this allows the class to manipulate data from several sources.57OutlineGradeBookTest.java(1 of 2)Line 10Line 13Declare and initialize gradesArray with 10 elements Pass gradesArray to GradeBook constructor 58OutlineGradeBookTest.java(2 of 2)Program output597.9 Multidimensional ArraysMultidimensional arraysTables with rows and columnsTwo-dimensional arraym-by-n array60Fig. 7.16 | Two-dimensional array with three rows and four columns. 617.9 Multidimensional Arrays (Cont.)Arrays of one-dimensional arrayDeclaring two-dimensional array b[2][2] int b[][] = { { 1, 2 }, { 3, 4 } };1 and 2 initialize b[0][0] and b[0][1]3 and 4 initialize b[1][0] and b[1][1] int b[][] = { { 1, 2 }, { 3, 4, 5 } };row 0 contains elements 1 and 2row 1 contains elements 3, 4 and 5627.9 Multidimensional Arrays (Cont.)Two-dimensional arrays with rows of different lengthsLengths of rows in array are not required to be the sameE.g., int b[][] = { { 1, 2 }, { 3, 4, 5 } };637.9 Multidimensional Arrays (Cont.)Creating two-dimensional arrays with array-creation expressions3-by-4 array int b[][];b = new int[ 3 ][ 4 ]; Rows can have different number of columns int b[][];b = new int[ 2 ][ ]; // create 2 rowsb[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int[ 3 ]; // create 3 columns for row 164OutlineInitArray.java(1 of 2)Line 9Line 10Use nested array initializers to initialize array1Use nested array initializers of different lengths to initialize array265OutlineInitArray.java(2 of 2)Line 26Line 27Program outputarray[row].length returns number of columns associated with row subscriptUse double-bracket notation to access two-dimensional array values667.9 Multidimensional Arrays (Cont.)Common multidimensional-array manipulations performed with for statementsMany common array manipulations use for statementsE.g., for ( int column = 0; column < a[ 2 ].length; column++ ) a[ 2 ][ column ] = 0; 677.10 Case Study: Class GradeBook Using a Two-Dimensional ArrayClass GradeBookOne-dimensional arrayStore student grades on a single examTwo-dimensional arrayStore grades for a single student and for the class as a whole68OutlineGradeBook.java(1 of 7)Line 7Line 10Declare two-dimensional array gradesGradeBook constructor accepts a String and a two-dimensional array 69OutlineGradeBook.java(2 of 7)70OutlineGradeBook.java(3 of 7)Lines 58-67Loop through rows of grades to find the lowest grade of any student 71OutlineGradeBook.java(4 of 7)Lines 79-88Lines 94-104Loop through rows of grades to find the highest grade of any student Calculate a particular student’s semester average 72OutlineGradeBook.java(5 of 7)Lines 115-119Calculate the distribution of all student grades 73OutlineGradeBook.java(6 of 7)74OutlineGradeBook.java(7 of 7)75OutlineGradeBookTest.java(1 of 2)Lines 10-19Declare gradesArray as 10-by-3 arrayEach row represents a student; each column represents an exam grade76OutlineGradeBookTest.java(2 of 2)Program output777.11 Variable-Length Argument ListsVariable-length argument listsUnspecified number of argumentsUse ellipsis () in method’s parameter listCan occur only once in parameter listMust be placed at the end of parameter listArray whose elements are all of the same type78OutlineVarargsTest.java(1 of 2)Line 7Lines 12-13Line 15Method average receives a variable length sequence of doublesCalculate the total of the doubles in the arrayAccess numbers.length to obtain the size of the numbers array79OutlineVarargsTest.java(2 of 2)Line 29Line 31Line 33Program outputInvoke method average with two argumentsInvoke method average with three argumentsInvoke method average with four arguments80 Common Programming Error 7.6Placing an ellipsis in the middle of a method parameter list is a syntax error. An ellipsis may be placed only at the end of the parameter list.817.12 Using Command-Line ArgumentsCommand-line argumentsPass arguments from the command lineString args[]Appear after the class name in the java commandjava MyClass a bNumber of arguments passed in from command lineargs.lengthFirst command-line argumentargs[ 0 ]82OutlineInitArray.java(1 of 2)Line 6Line 9Line 16Lines 20-21Lines 24-25Array args stores command-line argumentsCheck number of arguments passed in from the command lineObtain first command-line argumentObtain second and third command-line argumentsCalculate the value for each array element based on command-line arguments83OutlineInitArray.java(2 of 2)Program outputMissing command-line argumentsThree command-line arguments are 5, 0 and 4Three command-line arguments are 10, 1 and 2847.13 (Optional) GUI and Graphics Case Study: Drawing ArcsDraw rainbowUse arraysUse repetition statementUse Graphics method fillArc85OutlineDrawRainbow.java(1 of 2)Line 22Set component background to white86OutlineDrawRainbow.java(2 of 2)Lines 43-45Draw a filled semicircle87OutlineDrawRainbowTest.java88Fig. 7.24 | Drawing a spiral using drawLine (left) and drawArc (right). 897.14 (Optional) Software Engineering Case Study: Collaboration Among ObjectsCollaborationsWhen objects communicate to accomplish taskAccomplished by invoking operations (methods)One object sends a message to another object907.14 (Optional) Software Engineering Case Study (Cont.)Identifying the collaborations in a systemRead requirements document to findWhat ATM should do to authenticate a useWhat ATM should do to perform transactionsFor each action, decideWhich objects must interactSending objectReceiving object91Fig. 7.25 | Collaborations in the ATM system. 927.14 (Optional) Software Engineering Case Study (Cont.)Interaction DiagramsUsed to model interactions in the UMLCommunication diagramsAlso called collaboration diagramsEmphasize which objects participate in collaborationsSequence diagramsEmphasize when messages are sent between objects937.14 (Optional) Software Engineering Case Study (Cont.)Communication diagramsObjectsModeled as rectanglesContain names in the form objectName : classNameObjects are connected with solid linesMessages are passed alone these lines in the direction shown by arrowsName of message appears next to the arrow94Fig. 7.26 | Communication diagram of the ATM executing a balance inquiry. 957.14 (Optional) Software Engineering Case Study (Cont.)Sequence of messages in a communication diagramAppear to the left of a message nameIndicate the order in which the message is passedProcess in numerical order from least to greatest96Fig. 7.27 | Communication diagram for executing a balance inquiry. 977.14 (Optional) Software Engineering Case Study (Cont.)Sequence diagramsHelp model the timing of collaborationsLifelineDotted line extending down from an object’s rectangleRepresents the progression of timeActivationThin vertical rectangleIndicates that an object is executing98Fig. 7.28 | Sequence diagram that models a Withdrawal executing. 99Fig. 7.29 | Sequence diagram that models a Deposit executing. 100
Các file đính kèm theo tài liệu này:
- javahtp7e_07_1299_5661.ppt