java programming: from problem analysis to program design, 3e chapter 9 arrays

80
Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Post on 21-Dec-2015

231 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Java Programming: From Problem Analysis to Program Design, 3e

Chapter 9

Arrays

Page 2: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Chapter 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

Page 3: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Chapter 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

Page 4: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Array

• 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

Page 5: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

One-Dimensional Arrays

Page 6: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

One-Dimensional Arrays (continued)

Page 7: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

One-Dimensional Arrays (continued)

•intExp = number of components in array >= 0•0 <= indexExp <= intExp

Page 8: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

• Array num:int[] num = new int[5];

Arrays

Page 9: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Array List

Page 10: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Array List (continued)

Page 11: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Array List (continued)

Page 12: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Array List (continued)

Page 13: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Specifying Array Size During Program Execution

Page 14: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

• The initializer list contains values, called initial values, that are placed between braces and separated by commas

• Here, sales[0]= 12.25, sales[1]= 32.50, sales[2]= 16.90, sales[3]= 23.00, and sales[4]= 45.68

Array Initialization During Declaration

Page 15: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Using Initializer Lists

• 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

Page 16: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

• 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 • Do NOT confuse this with the length() method used

in strings. With arrays, length is a field.• The variable length can be directly accessed in a

program using the array name and the dot operator

Arrays and the Instance Variable length

Page 17: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Arrays and the Instance Variable length (continued)

int[] list = {10, 20, 30, 40, 50, 60};

• This statement creates the array list of six components and initializes the components using the values given– list.length is 6

int[] numList = new int[10];

• This statement creates the array numList of 10 components and initializes each component to 0

Page 18: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

• The value of numList.length is 10 numList[0] = 5;numList[1] = 10;numList[2] = 15;numList[3] = 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

• When dealing with an array that is only partially filled, it is good programming practice for your program to keep track of the number of filled elements in an array (i.e. use a variable)

Arrays and the Instance Variable length (continued)

Page 19: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Repeat: Keeping Track of Length

• Again: So far we’ve dealt only with arrays that we assume are filled with valid data. However it’s important to recognize that we will often (perhaps mostly) be dealing with arrays that are only partially filled with meaningful information. In these situations, we must have a variable that keeps track of how much of our array is “relevant”.

• This way, when we loop, we will NOT loop from i=0 until i < array.length.

• Instead we will loop from i=0 until

i < variable_keeping_track_of_array

Page 20: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

• Loops used to step through elements in array and perform operations

int[] list = new int[100];int i;

for (i = 0; i < list.length; i++) //process list[i], the (i + 1)th //element of list

for (i = 0; i < list.length; i++) list[i] = console.nextInt();

for (i = 0; i < list.length; i++) System.out.print(list[i] + " ");

Processing One-Dimensional Arrays

Page 21: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Arrays (continued) • Some operations on arrays:

– Initialize (e.g. set all values to -1)– Input data (e.g. from a file, from the user)– Output stored data – Find largest/smallest/sum/average of elements– Etc…

double[] arrSales = new double[10];int index;double largestSale, sum, average;

Page 22: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Code to Initialize Array to Specific Value (10.00)

for (index = 0; index < arrSales.length; index++) arrSales[index] = 10.00;

Page 23: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Code to Read Data into Array

for (index = 0; index < arrSales.length; index++) arrSales[index] = console.nextDouble();

Page 24: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Code to Print Array

for (index = 0; index < arrSales.length; index++) System.out.print(arrSales[index] + " ");

Page 25: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Code to Find Sum and Average of Array

sum = 0;for (index = 0; index < arrSales.length; index++) sum = sum + arrSales[index];

if (arrSales.length != 0) average = sum / arrSales.length;else average = 0.0;

Page 26: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Determining Largest Element in Array

maxIndex = 0;

for (index = 1; index < arrSales.length; index++) if (arrSales[maxIndex] < arrSales[index]) maxIndex = index;//Note: no need for braces here

largestSale = arrSales[maxIndex];

Page 27: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Determining Largest Element in Array (continued)

Page 28: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Determining Largest Element in Array (continued)

Page 29: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Array Index Out of Bounds

• Array in bounds if:0 <= index <= arraySize – 1

• If index < 0 or index > arraySize:

ArrayIndexOutOfBoundsException exception is thrown

We will discuss exceptions in a later lecture

• Base address: memory location of first component in array

Page 30: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

The Assignment Operators and Arrays

Supposing I were to write: listB = listA; ?

Page 31: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

The Assignment Operators and Arrays (continued)

Page 32: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

The Assignment Operators and Arrays (continued)

Page 33: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Relational Operators Arrays

• if (listA == listB) Will this work?- The expression listA == listB determines if the values of listA and listB are the same and thus determines whether listA and listB refer (point) to the same array- To determine whether listA and listB contain the same elements, you need to compare them element by element- You can write a method that returns true if two int arrays contain the same elements

Page 34: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

* Relational Operators and Arrays (continued)

boolean isEqualArrays(int[] firstArray, int[] secondArray){ if (firstArray.length != secondArray.length) return false; //could save us time!

for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) return false; return true;}

if (isEqualArrays(listA, listB))...

Page 35: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

* Arrays as Parameters to Methods

In this second method, we don’t use the field ‘length’. You would want to do this in a situation where you have an array that is not completely filled. (e.g. only 10 elements of an array of size 20 has meaningful values)

//Why the extra parameter to this method?

Page 36: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Methods for Array Processing

Page 37: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Methods for Array Processing (continued)

Page 38: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Methods for Array Processing (continued)

Page 39: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Methods for Array Processing (continued)

Page 40: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

* Arrays of Objects (important)• Can use arrays to manipulate objects• Example: create array named records with 20 objects

of type StudentRecord: StudentRecord[] records = new StudentRecord[20]

• Can fill records with instances of StudentRecord objects as follows:

for(int j=0; j <records.length; j++)

records[j] = new StudentRecord();

Page 41: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Array of String Objects

String[] nameList = new String[5];

nameList[0] = "Amanda Green";

nameList[1] = "Vijay Arora";

nameList[2] = "Sheila Mann";

nameList[3] = "Rohit Sharma";

nameList[4] = "Mandy Johnson";

Page 42: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Array of String Objects (continued)

Page 43: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

* Do not confuse the array as a whole with individual elements

• Consider the nameList[] array from the previous slide. If I were to ask you the data-type of nameList, many of you would be tempted to say ‘String’ or ‘array’. Yet neither is correct. The correct answer is “an array of String objects’

• If I were to ask you the data type of nameList[0] however, it is vitally important that you recognize that the answer is String.

For example• How might you check to see if the first element of the array is “Robert”?

if ( nameList[0].equals(“Robert”) ) { ...• How might you check to see if the first two elements of the array are identical?

if ( nameList[0].equals( nameList[1] ) ) { ...• How might you check the length of the last element of the array?

if ( nameList[namelist.length -1].length() ) { ...

Page 44: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Arrays of Objects contdYour book gives an example class called ‘Clock’ that has fields to represent hours, minutes and seconds:

public class Clock{ private int hr; //store hours private int min; //store minutes private int sec; //store seconds etc....

Suppose you had 100 employees who are paid on an hourly basis and you want to keep track of their arrival and departure times. You could create an array of 100 Clock objects to represent their arrival times, and also have an additional array of 100 Clock objects to represent their departure times.

Page 45: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Clock[] arrivalTimeEmp = new Clock[100];

Arrays of Objects (continued)

Page 46: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Instantiating Array Objectsfor (int j = 0; j < arrivalTimeEmp.length; j++) arrivalTimeEmp[j] = new Clock();

Page 47: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

arrivalTimeEmp[49].setTime(8, 5, 10);

Instantiating Array Objects (continued)

Page 48: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Array of objects continued

The toString() method has been written (overridden) for the class

You could output all of the information for each employee in the usual way:

for (int i=0; i<arrivalTimeEmp.length; i++) System.out.print( arrivalTimeEmp[i] );

… as long as?????

Page 49: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Arrays and Variable Length Parameter List

• The syntax to declare a variable length formal parameter (list) is:

dataType ... identifier

We will skip this section for 212. This is for your interest only at this point. Skip to the slide on the ‘foreach’ loop

Page 50: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Arrays and Variable Length Parameter List (continued)

Page 51: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Arrays and Variable Length Parameter List (continued)

Page 52: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Arrays 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

Page 53: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Arrays 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

Page 54: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

* for-each loop

• A nice shortcut for iterating through arrays– Only in more recent versions of Java (> version 5.0)

• The syntax to use this for loop to process the elements of an array is:

for (dataType identifier : arrayName) statements

• The data type of identifier must be the same as the data type of the components in the array

Page 55: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

for-each loop example

Read the colon as “in”. In the example below, we are saying for each ‘s’ in ‘names’…

for (String s : names){ System.out.println(s);}

Page 56: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

How the foreach loop works

total = 0; for (double num : list) total = total + num;

• The for statement in Line 2 is read as: for each num in list• The identifier num is initialized to list[0]• In the next iteration, the value of num is list[1], and so onfor (double num : numList){ if (max < num) max = num;}

Page 57: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

for-each loop example

for (double number : numbers){ System.out.println(number);}

Suppose you had an array called ‘numbers’ that is filled with doubles and wanted to output them using a foreach loop:

Page 58: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

for-each loop example

for (StudentRecord student : records){ System.out.println(student);}

Suppose you had an array of StudentRecords called ‘records’ and wanted to output them using a foreach loop:

(Note that toString() must be implemented in the StudentRecord class for the output to work properly.)

Page 59: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Limitations of the for-each loop

• The iterator (e.g. the ‘i’ that we are used to) is hidden in a for-each loop. So if you need to keep track of a specific index, for example, then this may not be your best choice of iterator. – You could declare a separate variable and increment it inside the body of

your loop, but in that case, you might as well just go with a regular for loop.

• Making changes to the array is not easily done either. For example, how would you increment each element of an integer array by +1? (Try it…)

• That being said, the for-each loop is extremely small, clear, and elegant. You should use it when possible!

Page 60: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Two-Dimensional ArraysSo far we have used arrays to store lists of data. What if, instead of a plain list, we wanted to keep track of something more like a table? For example, suppose you are a automobile dealer and you have an inventory that includes several BMWs, Toyotas, GMs, etc. In addition, for each make, you have several different colors. (For our example, the book assumes that each company sells only one type of model of each make!) So, for each make, we want to know how many red / brown / black / white / gray of each we have. This kind of data is best represented by a table as shown on the next slide.

Any kind of data that is best formed as a table, should probably be represented by a two-dimensional array.

We will create a two-dimensional array called inStock that keeps track of 6 different makes (GM, Ford, etc) and 5 different colors. The syntax to create such an array would be:int[][] inStock = new int[5][6];// Create a 2-D array of 5 rows, with 6 cells per row// NOTE: First index = ROW, second = COLUMN

Page 61: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Two-Dimensional Arrays

inStock[0][1] holds 7 inStock[4][2] holds 12

Page 62: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Two-Dimensional Arrays (continued)

Page 63: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

double[][] sales = new double[10][5];//e.g. keep track of 10 employees over 4 months

Two-Dimensional Arrays (continued)

Page 64: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

• intExp1, intExp2 >= 0• indexExp1 = row position• indexExp2 = column position

Accessing Array Elements

Page 65: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Accessing Array Elements (continued)

Page 66: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

• 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

• So how do you think you would determine the number of columns?

• Answer: matrix[0].length

Two-Dimensional Arrays and the Instance Variable length

Page 67: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Two-Dimensional Arrays and the Instance Variable length (continued)

• Each row of matrix is a one-dimensional array; matrix[0], in fact, refers to the first row

• The value of the expression:matrix[0].lengthis 15, the number of columns in the first row

• matrix[1].length gives the number of columns in the second row, which in this case is 15, and so on

Page 68: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Two-Dimensional (“Ragged”) Arrays:Different Number of columns in each row

Page 69: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

•Create columns

int[][] board = new int[5][]

Two-Dimensional Arrays: Special Cases:Different Number of columns in each row

Such arrays are known as “ragged” arrays

Page 70: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Two-Dimensional Array Initialization During Declaration

Page 71: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

• 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

Two-Dimensional Array Initialization During Declaration (continued)

Page 72: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Two-Dimensional Arrays: Special Cases:Initialization During Declaration

Page 73: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Processing Two-Dimensional Arrays• We will assume that our arrays are not ragged

– Keeps things simple for now

• Three ways to process 2-D arrays– Entire array– Particular row of array (row processing)– Particular column of array (column processing)

• Processing algorithms is similar to processing algorithms of one-dimensional arrays– BUT: We will need to nest our loops.

Page 74: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Two-Dimensional Arrays: Processing

Initialization

for (row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = 10;

Printfor (row = 0; row < matrix.length; row++){ for (col = 0; col < matrix[row].length; col++) System.out.printf("%7d", matrix[row][col]); System.out.println();}

Page 75: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Inputfor (int row = 0; row < matrix.length; row++){ for (int col = 0; col < matrix[row].length; col++) matrix[row][col] = console.nextInt();}

Sum by Rowfor (row = 0; row < matrix.length; row++){ sum = 0; for (col = 0; col < matrix[row].length; col++) sum = sum + matrix[row][col]; System.out.println("Sum of row " + (row + 1) + " = "+ sum);}

Two-Dimensional Arrays: Processing (continued)

Page 76: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Sum by Column for (col = 0; col < matrix[0].length; col++){ sum = 0; for (row = 0; row < matrix.length; row++) sum = sum + matrix[row][col]; System.out.println("Sum of column " + (col + 1) + " = " + sum);}

Two-Dimensional Arrays: Processing (continued)

Page 77: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Largest Element in Each Row

for (row = 0; row < matrix.length; row++){ largest = matrix[row][0]; for (col = 1; col < matrix[row].length; col++) { if (largest < matrix[row][col]) largest = matrix[row][col]; } System.out.println("The largest element of row " + (row + 1) + " = " + largest);}

Two-Dimensional Arrays: Processing (continued)

Page 78: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Largest Element in Each Column

for (col = 0; col < matrix[0].length; col++){ largest = matrix[0][col]; for (row = 1; row < matrix.length; row++) if (largest < matrix[row][col]) largest = matrix[row][col]; System.out.println("The largest element of col " + (col + 1) + " = " + largest);}

Two-Dimensional Arrays: Processing (continued)

Page 79: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Multidimensional Arrays

• Can define three-dimensional arrays or n-dimensional array (n can be any number)

• Syntax to declare and instantiate array

dataType[][]…[] arrayName = new dataType[intExp1][intExp2]…[intExpn];

• Syntax to access component

arrayName[indexExp1][indexExp2]…[indexExpn]

• intExp1, intExp2, ..., intExpn = positive integers• indexExp1,indexExp2, ..., indexExpn = non-negative integers

Page 80: Java Programming: From Problem Analysis to Program Design, 3e Chapter 9 Arrays

Loops to Process Multidimensional Arrays

double[][][] carDealers = new double[10][5][7];

for (i = 0; i < 10; i++) for (j = 0; j < 5; j++) for (k = 0; k < 7; k++) carDealers[i][j][k] = 10.00;