Download presentation
Presentation is loading. Please wait.
Published byVirginia Paul Modified over 9 years ago
1
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 Arrays
2
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 2 McGraw-Hill/Irwin Objectives Establish an array of variables and refer to individual elements in the array with variable subscripts. Use a for loop to step through an array. Use a loop to look up a matching value in an array. Accumulate totals using array elements. Distinguish between direct access and indirect access of a table. Combine the advantages of list objects with arrays. Store data in multidimensional arrays. Create and use an array of objects.
3
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 3 McGraw-Hill/Irwin Arrays An array is a series (or list) of values that all have the same data type and all have the same name. An array is used when you need to keep a series of values for later use such as reordering, calculating, or printing. An array can be a list of variables or a list of objects. Imagine trying to enter data for 500 products and each time the data is entered it has to be saved somewhere to enter the data for the next product. That somewhere is an array. To store multiple values use an array. An array is a series of individual variables, all referenced by the same name.
4
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 4 McGraw-Hill/Irwin Arrays Arrays are sometimes called lists, tables, or subscripted variables. The position in the array is represented by a subscript. For example strName[0], strName[1], … the numbers are subscripts. The subscripts (also known as index) are always in square brackets. The individual variable is called an element in the array. The first element in the array always starts with a subscript of zero. If you have 10 elements, the subscripts will go from 0 to 9.
5
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 5 McGraw-Hill/Irwin Subscripts Subscripts may be constants, variables, or numeric expressions. Although, subscripts have to integers, the non-integers are rounded off. To know how many elements in the array, you must specify the number of elements in the array at the time of initialization.
6
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 6 McGraw-Hill/Irwin Declaring an Array You can choose several techniques for a declaring an array.
7
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 7 McGraw-Hill/Irwin Using the new Keyword to declare an Array—General Format DataType VariableName[] = new DataType [size]; DataType[] VariableName = new DataType[size];
8
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 8 McGraw-Hill/Irwin Using the new Keyword to Declare an Array—Examples int intEmployeeCount[] = new int[50]; float[] fltTotal = new float[10]; String strName[] = new String[25];
9
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 9 McGraw-Hill/Irwin Declaring an Array The declaration statement allocates storage for a specified number of elements and initializes each element to the default value for the data type. For example, for an integer array all the elements will be initialized to 0 and for a String array all the elements will be initialized to empty string.
10
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 10 McGraw-Hill/Irwin
11
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 11 McGraw-Hill/Irwin Using an Initializer to Create an Array—Examples int intDepartmentNumber[] = {423, 633, 672, 981}; String strDepartmentNames[] = {"Accounting", "Information Systems", "Marketing", "Sales"};
12
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 12 McGraw-Hill/Irwin More on Subscripts A subscript must reference a valid element in the array. If an array has 10 elements in the list and you try and reference the 15th element in the list, array will throw an exception. Java rounds up fractional subscripts such as 2 1 / 2.
13
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 13 McGraw-Hill/Irwin Iterating Through an Array You can use a for loop to iterate through all the elements in an array. The following loop initializes a loop index to 0 to access the first element in the fltSales array. As intIndex is incremented each element is added to the total. for(int intIndex = 0; intIndex < 10; intIndex ++) { fltTotal += fltSales[intIndex]; }
14
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 14 McGraw-Hill/Irwin Using Array Elements for Accumulators Array elements are regular variables and perform in the same ways as all variables used so far. You may use subscripted variables for counters or accumulators.
15
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 15 McGraw-Hill/Irwin Catching User Input Errors If the user enters an invalid number you can check he range with an if statement or catch the exception. If you choose to catch an exception rather than test with an if statement, check for an ArrayIndexOutOfBoundsException. Using the group number, as an index to the array is a technique called direct reference.
16
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 16 McGraw-Hill/Irwin Shows the Applet and the Variables Used intTotal[] array 0 0 0 10 0 0 0 0 [0] [1] [2] [3] [4] [5] [6] [7] intGroupNum (txtGroup –1) 3 txtGroup txtSale
17
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 17 McGraw-Hill/Irwin Table Lookup Considering the last example of the troops, whose numbers were from 1 to 8. It is not always that the groups have numbers that are sequentially numbered. The best way is to declare two arrays. One array that holds the group numbers and the other array holds the total sales. The user will type the group number and the sale. The array will look up the group number and the subscript of the group number will be used in the array for the total sales. The technique used to find the subscript is called table lookup. The subscript will serve to keep track of the total for each group.
18
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 18 McGraw-Hill/Irwin Each Element in the intGroupNumArray Corresponds to One Element of the intTotal Array [0] [1] [2] [3] [4] [5] [6] [7] [0] [1] [2] [3] [4] [5] [6] [7] 101 103 110 115 121 123 130 145 101 103 110 115 121 123 130 145 intGroupNumArray[ ] intTotal[ ] array
19
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 19 McGraw-Hill/Irwin [0] [1] [2] [3] [4] [5] [6] [7] [0] [1] [2] [3] [4] [5] [6] [7] 101 103 110 115 121 123 130 145 0 0 10 0 0 0 0 0 intGroupNumArray[ ]intTotal[ ] array txtGroup txtSale intGroupNum 110 intGroupSub 2 A Lookup Operation
20
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 20 McGraw-Hill/Irwin Flowchart of the Logic of a Table Lookup Operation
21
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 21 McGraw-Hill/Irwin Using Lists with Arrays Instead of storing information in an array for the group numbers, store them in a List or Choice component. This is would be a more friendly and efficient solution. The user can select the group number from the list and the index can be used for the array. The getSelectedIndex method will determine the array subscript. You can print the group numbers, using the getItem method.
22
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 22 McGraw-Hill/Irwin Allow the User to Select a Group Using the Choice List
23
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 23 McGraw-Hill/Irwin Multidimensional Arrays You may need two or more subscripts to identify tabular data, where data is arranged in rows and columns.
24
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 24 McGraw-Hill/Irwin The Declaration Statement for Two- Dimensional Arrays—General Format DataType ArrayName[NumberRows][NumberColumns];
25
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 25 McGraw-Hill/Irwin The Declaration Statement for Two- Dimensional Arrays—Examples String strName[][] = new String[3][4]; float fltRate[][] = {{1.0f, 1.5f, 1.65f, 1.85f}, {1.58f, 2.0f, 2.4f, 3.05f}, {1.71f, 2.52f, 3.10f, 4.0f}, {2.04f, 3.12f, 4.0f, 5.01f}, {2.52f, 3.75f, 5.10f, 7.25f}};
26
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 26 McGraw-Hill/Irwin Multidimensional Arrays The strName example has three rows and four columns. The second example uses an initializer to set values, one row at a time. You must always use two subscripts when referring to individual elements of the table. Specify the row with first subscript and the column with second subscript. The elements of the array may be used in the same ways as any other variable – in accumulators, counts, reference field, displaying text and conditions.
27
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 27 McGraw-Hill/Irwin Summing a Two-Dimensional Table You can find the sum of a table in various ways. You may sum either the columns or the rows of the table; or as in a cross-foot, or you may sum the figures in both directions and double-check the totals. To sum the array in both directions each column needs one total field, and each row needs one total field.
28
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 28 McGraw-Hill/Irwin Two One-Dimensional Arrays Hold Totals for the Two-Dimensional Array
29
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 29 McGraw-Hill/Irwin Lookup Operation for Two- Dimensional Tables When you look up items in a two-dimensional table, you can use the same techniques discussed with single dimensional arrays: direct reference and table lookup. The limitations are the same. Direct reference – row and column subscripts must be readily available. A table lookup – most common technique; require additional one-dimensional arrays or list to aid in the lookup process.
30
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 30 McGraw-Hill/Irwin This Shipping Rate Table in a Two-Dimensional Array Can Be Used to Look Up the Correct Shipping Charges 1.001.501.651.85 1.582.002.403.05 1.712.523.104.00 2.043.124.005.01 2.523.755.107.25 Shipping Rate Table fltRate array 1 lb. >10 lb. 10 lb. 5 lb. 3 lb. Zone A Zone B Zone C Zone D Weight (not to Exceed) intWeightSub 1 intZoneSub 3 intWeightSub uses the index of 1stWeight intZoneSub uses the index of 1stZone
31
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 31 McGraw-Hill/Irwin Using TextFields If you are using text fields for data entry rather than lists, the input requires more validation. You must validate both the entries before you can find the correct value.
32
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 32 McGraw-Hill/Irwin Creating an Array of Objects You can create arrays of classes or create arrays of components. Using a class requires the keyword new to create an array of objects. For example: Course Courses[] = new Course[3]; Label lblGroupNumber[] = new Label[8]; The objects in the array are not automatically instantiated. Use a loop to instantiate each object, once again using the keyword new. Usually you will place the following code in the init.
33
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 33 McGraw-Hill/Irwin FindCourseApplet Looks Up the Course Number in the Courses Array and Fills in the Room and Unit Information Courses[0].strRoom Courses[0].fltUnits Courses array CIS 10A26D-3083.5 COMP 1617-11A3.5 CIS 2817-134.0 Courses[0] Courses[1] Courses[2] strDescstrRoom fltUnits
34
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 34 McGraw-Hill/Irwin An Array of Course Objects Instead, you can refer to objectName-dot-variableName (Courses[0].strRoom).
35
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 35 McGraw-Hill/Irwin An Array of Components You can also create arrays of components. This technique is handy when you need several components of the same type, especially if you need to reference the components with an index.
36
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 36 McGraw-Hill/Irwin Use Two Arrays of Labels to Display the Group Numbers and the Total for Each Group
37
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 37 McGraw-Hill/Irwin Java Arrays for C++ and Visual Basic Programmers Arrays in Java must have defined limits differing from those in C++. Java does not allow pointer arithmetic to access array elements. Both features enhance security in Java. In Visual Basic, you can declare array with subscripts beginning with any number, such as (1 to 10) or (-10 to 10), which Java does not allow. Visual Basic also has dynamic arrays, which can be resized during program execution.
38
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 38 McGraw-Hill/Irwin Vectors In reality, Java does have resizable or dynamic arrays – they are called vectors. A Vector is a class that is similar to an array. It holds multiple values and is referenced by an index. In addition, a vector automatically grows when more elements are needed. The Vector class has many methods to aid creating the elements, adding and removing elements, and searching for particular elements.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.