Download Programming with Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Programming with Java
1
Chapter 9
Arrays
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
2
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
3
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
4
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
5
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
6
Declaring an Array
• You can choose several techniques for a declaring an array.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
7
Using the new Keyword to declare
an Array—General Format
DataType VariableName[] = new DataType [size];
DataType[] VariableName = new DataType[size];
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
8
Using the new Keyword to
Declare an Array—Examples
int intEmployeeCount[] = new int[50];
float[] fltTotal = new float[10];
String strName[] = new String[25];
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
9
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
McGraw-Hill/Irwin
10
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
11
Using an Initializer to Create an
Array—Examples
int intDepartmentNumber[] = {423, 633, 672, 981};
String strDepartmentNames[] = {"Accounting", "Information Systems", "Marketing",
"Sales"};
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
12
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 21/2.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
13
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];
}
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
14
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
15
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
16
Shows the Applet and the Variables Used
intGroupNum
(txtGroup –1)
3
intTotal[] array
[0]
0
[1]
0
[2]
0
[3]
10
[4]
0
[5]
0
[6]
0
[7]
0
McGraw-Hill/Irwin
txtGroup
txtSale
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
17
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
18
Each Element in the intGroupNumArray Corresponds
to One Element of the intTotal Array
intGroupNumArray[ ]
McGraw-Hill/Irwin
intTotal[ ] array
[0]
101
[0]
101
[1]
103
[1]
103
[2]
110
[2]
110
[3]
115
[3]
115
[4]
121
[4]
121
[5]
123
[5]
123
[6]
130
[6]
130
[7]
145
[7]
145
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
19
A Lookup Operation
intGroupSub
2
intGroupNumArray[ ]
intTotal[ ] array
intGroupNum
110
txtGroup
txtSale
[0]
101
[0]
0
[1]
103
[1]
0
[2]
110
[2]
10
[3]
115
[3]
0
[4]
121
[4]
0
[5]
123
[5]
0
[6]
130
[6]
0
[7]
145
[7]
0
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
20
Flowchart of
the Logic of a
Table Lookup
Operation
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
21
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
22
Allow the User to Select a Group
Using the Choice List
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
23
Multidimensional Arrays
• You may need two or more subscripts to identify tabular data,
where data is arranged in rows and columns.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
24
The Declaration Statement for TwoDimensional Arrays—General Format
DataType ArrayName[NumberRows][NumberColumns];
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
25
The Declaration Statement for TwoDimensional 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}};
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
26
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
27
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
28
Two One-Dimensional Arrays Hold
Totals for the Two-Dimensional Array
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
29
Lookup Operation for TwoDimensional 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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
30
This Shipping Rate Table in a Two-Dimensional Array
Can Be Used to Look Up the Correct Shipping Charges
Shipping Rate Table
fltRate array
intWeightSub
1
Weight (not
to Exceed)
intWeightSub
uses the index
of 1stWeight
intZoneSub
3
Zone
A
Zone
B
Zone
C
Zone
D
1 lb.
1.00
1.50
1.65
1.85
3 lb.
1.58
2.00
2.40
3.05
5 lb.
1.71
2.52
3.10
4.00
10 lb.
2.04
3.12
4.00
5.01
>10 lb.
2.52
3.75
5.10
7.25
intZoneSub
uses the index
of 1stZone
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
31
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
32
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
33
FindCourseApplet Looks Up the Course Number
in the Courses Array and Fills in the Room and
Unit Information
Courses array
strDesc
Courses[0].strRoom
strRoom
fltUnits
Courses[0] CIS 10A
26D-308
3.5
Courses[1] COMP 16
17-11A
3.5
Courses[2] CIS 28
17-13
4.0
Courses[0].fltUnits
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
34
An Array of Course Objects
• Instead, you can refer to objectName-dot-variableName
(Courses[0].strRoom).
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
35
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
36
Use Two Arrays of Labels to
Display the Group Numbers
and the Total for Each Group
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
37
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
38
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.
McGraw-Hill/Irwin
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.