Title: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9
1Java Programming From Problem Analysis to
Program Design, 3eChapter 9
2Chapter Objectives
- Learn about arrays
- Explore how to declare and manipulate data into
arrays - Understand the meaning of array index out of
bounds - Become familiar with the restrictions on array
processing
3Chapter Objectives (continued)
- Discover how to pass an array as a parameter to a
method - Discover how to manipulate data in a
two-dimensional array - Learn about multidimensional arrays
4Array
- Definition structured data type with a fixed
number of elements - Elements of an array are also called components
of the array - Every element is of the same type
- Elements are accessed using their relative
positions in the array
5One-Dimensional Arrays
6One-Dimensional Arrays (continued)
7One-Dimensional Arrays (continued)
- intExp number of components in array gt 0
- 0 lt indexExp lt intExp
8 Array numint num new int5
Arrays
9Array List
10Array List (continued)
11Array List (continued)
12Array List (continued)
13- Specifying Array Size During Program Execution
14Array Initialization During Declaration
- The initializer list contains values, called
initial values, that are placed between braces
and separated by commas - Here, sales0 12.25, sales1 32.50, sales2
16.90, sales3 23.00, and sales4 45.68
15Array Initialization During Declaration
(continued)
- When declaring and initializing arrays, the size
of the array is determined by the number of
initial values within the braces - If an array is declared and initialized
simultaneously, we do not use the operator new to
instantiate the array object
16Arrays and the Instance Variable length
- Associated with each array that has been
instantiated, there is a public (final) instance
variable length - The variable length contains the size of the
array - The variable length can be directly accessed in a
program using the array name and the dot operator - int list 10, 20, 30, 40, 50, 60
17Arrays and the Instance Variable length
(continued)
- This statement creates the array list of six
components and initializes the components using
the values given - Here list.length is 6
- int numList new int10
- This statement creates the array numList of 10
components and initializes each component to 0
18Arrays and the Instance Variable length
(continued)
- The value of numList.length is 10
- numList0 5
- numList1 10
- numList2 15
- numList3 20
- These statements store 5, 10, 15, and 20,
respectively, in the first four components of
numList - You can store the number of filled elements, that
is, the actual number of elements, in the array
in a variable, say numOfElement - It is a common practice for a program to keep
track of the number of filled elements in an array
19Processing One-Dimensional Arrays
- Loops used to step through elements in array and
perform operations - int list new int100
- int i
- for (i 0 i lt list.length i)
- //process listi, the (i 1)th
- //element of list
- for (i 0 i lt list.length i)
- listi console.nextInt()
- for (i 0 i lt list.length i)
- System.out.print(listi " ")
20Arrays (continued)
- Some operations on arrays
- Initialize
- Input data
- Output stored data
- Find largest/smallest/sum/average of elements
double sales new double10 int
index double largestSale, sum, average
21Code to Initialize Array to Specific Value (10.00)
for (index 0 index lt sales.length
index) salesindex 10.00
22Code to Read Data into Array
for (index 0 index lt sales.length
index) salesindex
console.nextDouble()
23Code to Print Array
for (index 0 index lt sales.length
index) System.out.print(salesindex
" ")
24Code to Find Sum and Average of Array
sum 0 for (index 0 index lt sales.length
index) sum sum
salesindex if (sales.length ! 0) average
sum / sales.length else average 0.0
25Determining Largest Element in Array
maxIndex 0 for (index 1 index lt
sales.length index) if
(salesmaxIndex lt salesindex) maxIndex
index largestSale salesmaxIndex
26Determining Largest Element in Array (continued)
27Determining Largest Element in Array (continued)
28Array Index Out of Bounds
- Array in bounds if
- 0 lt index lt arraySize 1
- If index lt 0 or index gt arraySize
- ArrayIndexOutOfBoundsException exception is
thrown - Base address memory location of first component
in array
29Declaring Arrays as Formal Parameters to Methods
- A general syntax to declare an array as a formal
parameter - dataType arrayName
- public static void arraysAsFormalParameter(int
listA, - double listB, int num)
-
- //...
-
- int intList new int10
- double doubleNumList new double15
- int number
- arraysAsFormalParameter(intList, doubleNumList,
number)
30The Assignment Operators and Arrays
31The Assignment Operators and Arrays (continued)
32The Assignment Operators and Arrays (continued)
33Relational Operators Arrays
- if (listA listB)...
- - The expression listA listB determines if the
values of listA and listB are the same and thus
determines whether listA and listB refer to the
same array - - To determine whether listA and listB contain
the same elements, you need to compare them
component by component - - You can write a method that returns true if two
int arrays contain the same elements
34Relational Operators and Arrays (continued)
boolean isEqualArrays(int firstArray,
int secondArray) if
(firstArray.length ! secondArray.length)
return false for (int index 0 index lt
firstArray.length
index) if (firstArrayindex !
secondArrayindex) return false
return true if (isEqualArrays(listA,
listB)) ...
35Arrays as Parameter Methods
36Methods for Array Processing
37Methods for Array Processing (continued)
38Methods for Array Processing (continued)
39Methods for Array Processing (continued)
40Parallel Arrays
- Arrays are parallel if corresponding components
hold related information
41Arrays of Objects
- Can use arrays to manipulate objects
- Example create array named array1 with N objects
of type T - T array1 new TN
- Can instantiate array1 as follows
- for(int j0 j ltarray1.length j)
- array1j new T()
42Array of String Objects
- String nameList new String5
- nameList0 "Amanda Green"
- nameList1 "Vijay Arora"
- nameList2 "Sheila Mann"
- nameList3 "Rohit Sharma"
- nameList4 "Mandy Johnson"
43Array of String Objects (continued)
44Clock arrivalTimeEmp new Clock100
Arrays of Objects (continued)
45Instantiating Array Objects
for (int j 0 j lt arrivalTimeEmp.length j)
arrivalTimeEmpj new Clock()
46Instantiating Array Objects (continued)
arrivalTimeEmp49.setTime(8, 5, 10)
47Arrays and Variable Length Parameter List
- The syntax to declare a variable length formal
parameter (list) is - dataType ... identifier
48Arrays and Variable Length Parameter List
(continued)
49Arrays and Variable Length Parameter List
(continued)
50Arrays and Variable Length Parameter List
(continued)
- A method can have both a variable length formal
parameter and other formal parameters consider
the following method heading - public static void myMethod(String name, double
num, int ... intList) - The formal parameter name is of type String, the
formal parameter num is of type double, and the
formal parameter intList is of variable length - The actual parameter corresponding to intList can
be an int array or any number of int variables
and/or int values
51Arrays and Variable Length Parameter List
(continued)
- A method can have at most one variable length
formal parameter - If a method has both a variable length formal
parameter and other types of formal parameters,
then the variable length formal parameter must be
the last formal parameter of the formal parameter
list
52foreach loop
- The syntax to use this for loop to process the
elements of an array is - for (dataType identifier arrayName)
- statements
- identifier is a variable and the data type of
identifier is the same as the data type of the
array components
53foreach loop (continued)
- sum 0
- for (double num list)
- sum sum num
- The for statement in Line 2 is read for each num
in list - The identifier num is initialized to list0
- In the next iteration, the value of num is
list1, and so on - for (double num numList)
-
- if (max lt num)
- max num
54Two-Dimensional Arrays
55Two-Dimensional Arrays (continued)
56double sales new double105
Two-Dimensional Arrays (continued)
57Accessing Array Elements
- intExp1, intExp2 gt 0
- indexExp1 row position
- indexExp2 column position
58Accessing Array Elements (continued)
59Two-Dimensional Arrays and the Instance Variable
length
- This statement declares and instantiates a
two-dimensional array matrix of 20 rows and 15
columns - The value of the expression
- matrix.length
- is 20, the number of rows
60Two-Dimensional Arrays and the Instance Variable
length (continued)
- Each row of matrix is a one-dimensional array
matrix0, in fact, refers to the first row - The value of the expression
- matrix0.length
- is 15, the number of columns in the first row
- matrix1.length gives the number of columns in
the second row, which in this case is 15, and so
on
61Two-Dimensional Arrays Special Cases
62Two-Dimensional Arrays Special Cases (continued)
63Two-Dimensional Array Initialization During
Declaration
64Two-Dimensional Array Initialization During
Declaration (continued)
- To initialize a two-dimensional array when it is
declared - - The elements of each row are enclosed within
braces and separated by commas - - All rows are enclosed within braces
65Two-Dimensional Array Initialization During
Declaration (continued)
66Two-Dimensional Arrays (continued)
- Three ways to process 2-D arrays
- Entire array
- Particular row of array (row processing)
- Particular column of array (column processing)
- Processing algorithms similar to processing
algorithms of one-dimensional arrays
67Two-Dimensional Arrays Processing
Initialization for (row 0 row lt
matrix.length row) for (col 0 col lt
matrixrow.length col)
matrixrowcol 10
Print for (row 0 row lt matrix.length
row) for (col 0 col lt
matrixrow.length col)
System.out.printf("7d",
matrixrowcol) System.out.println()
68Two-Dimensional Arrays Processing (continued)
Input for (row 0 row lt matrix.length row)
for (col 0 col lt matrixrow.length
col) matrixrowcol
console.nextInt()
Sum by Rowfor (row 0 row lt matrix.length
row) sum 0 for (col 0 col lt
matrixrow.length col)
sum sum matrixrowcol
System.out.println("Sum of row " (row 1)
" " sum)
69Two-Dimensional Arrays Processing (continued)
Sum by Column for (col 0 col lt
matrix0.length col) sum 0 for
(row 0 row lt matrix.length row)
sum sum matrixrowcol
System.out.println("Sum of column " (col 1)
" " sum)
70Two-Dimensional Arrays Processing (continued)
Largest Element in Each Row for (row 0 row lt
matrix.length row) largest
matrixrow0 for (col 1 col lt
matrixrow.length col)
if (largest lt matrixrowcol)
largest matrixrowcol
System.out.println("The largest element of row "
(row 1) " "
largest)
71Two-Dimensional Arrays Processing (continued)
Largest Element in Each Column for (col 0 col
lt matrix0.length col) largest
matrix0col for (row 1 row lt
matrix.length row) if (largest lt
matrixrowcol) largest
matrixrowcol System.out.println("The
largest element of col "
(col 1) " " largest)
72Multidimensional Arrays
- Can define three-dimensional arrays or
n-dimensional array (n can be any number) - Syntax to declare and instantiate array
- dataType arrayName new
- dataTypeintExp1intExp2intExpn
- Syntax to access component
- arrayNameindexExp1indexExp2indexExpn
- intExp1, intExp2, ..., intExpn positive
integers - indexExp1,indexExp2, ..., indexExpn
non-negative integers
73Loops to Process Multidimensional Arrays
double carDealers new double1057
for (i 0 i lt 10 i) for (j 0 j lt 5
j) for (k 0 k lt 7 k)
carDealersijk 10.00
74Programming Example Text Processing
- Program reads given text outputs the text as
is prints number of lines and number of times
each letter appears in text - Input file containing text to be processed
- Output file containing text, number of lines,
number of times letter appears in text
75Programming Example Solution Text Processing
- An array of 26 representing the letters in the
alphabet - Three methods
- copyText
- characterCount
- writeTotal
- Value in appropriate index incremented using
methods and depending on character read from text
76Chapter Summary
- Arrays
- Definition
- Uses
- Different Arrays
- One-dimensional
- Two-dimensional
- Multidimensional (n-dimensional)
- Arrays of objects
- Parallel arrays
77Chapter Summary (continued)
- Declaring arrays
- Instantiating arrays
- Processing arrays
- Entire array
- Row processing
- Column processing
- Common operations and methods performed on arrays
- Manipulating data in arrays