programming lecture 9

Upload: reijen-inciong

Post on 06-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Programming Lecture 9

    1/77

  • 8/3/2019 Programming Lecture 9

    2/77

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

    Chapter Objectives Learn about arrays

    Explore how to declare and manipulate datainto arrays

    Understand the meaning of array index out

    of bounds

    Become familiar with the restrictions on

    array processing

  • 8/3/2019 Programming Lecture 9

    3/77

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

    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

  • 8/3/2019 Programming Lecture 9

    4/77

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

    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

  • 8/3/2019 Programming Lecture 9

    5/77

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

    One-Dimensional Arrays

  • 8/3/2019 Programming Lecture 9

    6/77

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

    One-Dimensional Arrays

    (continued)

  • 8/3/2019 Programming Lecture 9

    7/77

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

    One-Dimensional Arrays

    (continued)

    intExp = number of components in array >= 0

    0

  • 8/3/2019 Programming Lecture 9

    8/77

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

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

    Arrays

  • 8/3/2019 Programming Lecture 9

    9/77

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

    Array List

  • 8/3/2019 Programming Lecture 9

    10/77

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

    Array List (continued)

  • 8/3/2019 Programming Lecture 9

    11/77

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

    Array List (continued)

  • 8/3/2019 Programming Lecture 9

    12/77

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

    Array List (continued)

  • 8/3/2019 Programming Lecture 9

    13/77

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

    Specifying Array Size During

    Program Execution

  • 8/3/2019 Programming Lecture 9

    14/77

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

    The initializer list contains values, called initial

    values, that are placed between braces andseparated by commas

    Here, sales[0]= 12.25, sales[1]=32.50, sales[2]= 16.90, sales[3]=

    23.00, andsal

    es

    [4]= 45.68

    Array Initialization During Declaration

  • 8/3/2019 Programming Lecture 9

    15/77

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

    Array 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 operatornew to instantiate the array object

  • 8/3/2019 Programming Lecture 9

    16/77

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

    Associated with each array that has beeninstantiated, there is a public (final) instancevariable length

    The variable length contains the size of the array The variable length can be directly accessed in aprogram using the array name and the dot operator

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

    Arrays and the Instance Variablelength

  • 8/3/2019 Programming Lecture 9

    17/77

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

    Arrays 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 int[10];

    This statement creates the array numListof 10 components and initializes eachcomponent to 0

  • 8/3/2019 Programming Lecture 9

    18/77

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

    The value ofnumList.length is 10numList[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 ofnumList

    You can store the number of filled elements, that is, theactual number of elements, in the array in a variable, saynumOfElement

    It is a common practice for a program to keep track of thenumber of filled elements in an array

    Arrays and the Instance Variablelength (continued)

  • 8/3/2019 Programming Lecture 9

    19/77

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

    Loops used to step through elements in arrayand perform operations

    int[] list = new int[100];

    int i;

    for (i = 0; i < list.length; i++)

    //processlist[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-DimensionalArrays

  • 8/3/2019 Programming Lecture 9

    20/77

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

    Arrays (continued)

    Some operations on arrays:

    Initialize

    Input data

    Output stored data

    Find largest/smallest/sum/average of elements

    double[] sales = new double[10];

    int index;

    double largestSale, sum, average;

  • 8/3/2019 Programming Lecture 9

    21/77

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

    Code to Initialize Array to

    Specific Value (10.00)

    for (index = 0; index < sales.length;

    index++)sales[index] = 10.00;

  • 8/3/2019 Programming Lecture 9

    22/77

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

    Code to Read Data into Array

    for (index = 0; index < sales.length;

    index++)sales[index] = console.nextDouble();

  • 8/3/2019 Programming Lecture 9

    23/77

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

    Code to Print Array

    for (index = 0; index < sales.length;

    index++)System.out.print(sales[index] + " ");

  • 8/3/2019 Programming Lecture 9

    24/77

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

    Code to Find Sum and Average

    of Arraysum = 0;

    for (index = 0; index < sales.length;

    index++)sum = sum + sales[index];

    if (sales.length != 0)

    average = sum / sales.length;

    else

    average = 0.0;

  • 8/3/2019 Programming Lecture 9

    25/77

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

    Determining Largest Element in

    Array

    maxIndex = 0;

    for (index = 1; index < sales.length;

    index++)

    if (sales[maxIndex] < sales[index])

    maxIndex = index;

    largestSale = sales[maxIndex];

  • 8/3/2019 Programming Lecture 9

    26/77

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

    Determining Largest Element in

    Array (continued)

  • 8/3/2019 Programming Lecture 9

    27/77

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

    Determining Largest Element in

    Array (continued)

  • 8/3/2019 Programming Lecture 9

    28/77

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

    Array Index Out of Bounds

    Array in bounds if:0

  • 8/3/2019 Programming Lecture 9

    29/77

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

    Declaring Arrays as Formal

    Parameters to Methods A general syntax to declare an array as a formal

    parameterdataType[] arrayName

    public static void arraysAsFormalParameter(int[] listA,

    double[] listB, int num){

    //...

    }

    int[] intList = new int[10];

    doubl

    e[] doubl

    eNumLis

    t = new doubl

    e[15];int number;

    arraysAsFormalParameter(intList, doubleNumList,number);

  • 8/3/2019 Programming Lecture 9

    30/77

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

    The Assignment Operators and

    Arrays

  • 8/3/2019 Programming Lecture 9

    31/77

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

    The Assignment Operators and

    Arrays (continued)

  • 8/3/2019 Programming Lecture 9

    32/77

  • 8/3/2019 Programming Lecture 9

    33/77

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

    Relational Operators Arrays

    if (listA == listB)...

    - The expression listA == listB determines if

    the values oflistA and listB are the same and thus

    determines whetherlistA and listB refer to the

    same array- To determine whetherlistA 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

  • 8/3/2019 Programming Lecture 9

    34/77

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

    Relational Operators and Arrays

    (continued)boolean isEqualArrays(int[] firstArray,

    int[] secondArray)

    {

    if (firstArray.length != secondArray.length)

    return false;

    for (int index = 0; index < firstArray.length;

    index++)

    if (firstArray[index] != secondArray[index])

    return false;

    return true;

    }

    if (isEqualArrays(listA, listB))

    ...

  • 8/3/2019 Programming Lecture 9

    35/77

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

    Arrays as Parameter Methods

  • 8/3/2019 Programming Lecture 9

    36/77

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

    Methods for Array Processing

  • 8/3/2019 Programming Lecture 9

    37/77

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

    Methods for Array Processing

    (continued)

  • 8/3/2019 Programming Lecture 9

    38/77

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

    Methods for Array Processing

    (continued)

  • 8/3/2019 Programming Lecture 9

    39/77

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

    Methods for Array Processing

    (continued)

  • 8/3/2019 Programming Lecture 9

    40/77

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

    Parallel Arrays Arrays are parallel if corresponding

    components hold related information

  • 8/3/2019 Programming Lecture 9

    41/77

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

    Arrays of Objects

    Can use arrays to manipulate objects Example: create array named array1 with N

    objects of type T

    T[] array1 = new T[N] Can instantiate array1 as follows:

    for(int j=0; j

  • 8/3/2019 Programming Lecture 9

    42/77

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

    Array ofString Objects

    String[] nameList = new String[5];

    nameList[0] = "Amanda Green";

    nameLi

    st[1] = "Vij

    ay Aror

    a";

    nameList[2] = "Sheila Mann";

    nameList[3] = "Rohit Sharma";

    nameList[4] = "Mandy Johnson";

  • 8/3/2019 Programming Lecture 9

    43/77

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

    Array ofString Objects

    (continued)

  • 8/3/2019 Programming Lecture 9

    44/77

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

    Clock[] arrivalTimeEmp = new Clock[100];

    Arrays of Objects (continued)

  • 8/3/2019 Programming Lecture 9

    45/77

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

    Instantiating Array Objectsfor (int j = 0; j < arrivalTimeEmp.length; j++)

    arri

    valTimeEmp[j] = new

    Clock();

  • 8/3/2019 Programming Lecture 9

    46/77

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

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

    Instantiating Array Objects (continued)

  • 8/3/2019 Programming Lecture 9

    47/77

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

    Arrays and Variable Length

    Parameter List The syntax to declare a variable length formal

    parameter (list) is:

    dataType ... identifier

    A d V i bl L th

  • 8/3/2019 Programming Lecture 9

    48/77

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

    Arrays and Variable Length

    Parameter List (continued)

  • 8/3/2019 Programming Lecture 9

    49/77

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

    Arrays and Variable Length

    Parameter List (continued)

    A d V i bl L h

  • 8/3/2019 Programming Lecture 9

    50/77

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

    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 parameternum is of type double, and the

    formal parameterintList

    is of variable length The actual parameter corresponding to intList can

    be an int array or any number ofint variables and/or

    int values

  • 8/3/2019 Programming Lecture 9

    51/77

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

    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 lengthformal parameter and other types of formal

    parameters, then the variable length formal

    parameter must be the last formal parameterof the formal parameter list

  • 8/3/2019 Programming Lecture 9

    52/77

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

    foreach loop

    The syntax to use this for loop to process theelements of an array is:

    for (dataType identifier : arrayName)

    statements

    identifier is a variable and the data type ofidentifier is the same as the data type of the array

    components

  • 8/3/2019 Programming Lecture 9

    53/77

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

    foreach 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 identifiernum is initialized to list[0 In the next iteration, the value ofnum is list[1], and so

    on

    for (double num : numList)

    {if (max < num)

    max = num;

    }

  • 8/3/2019 Programming Lecture 9

    54/77

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

    Two-Dimensional Arrays

  • 8/3/2019 Programming Lecture 9

    55/77

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

    Two-Dimensional Arrays

    (continued)

    T Di i l A

  • 8/3/2019 Programming Lecture 9

    56/77

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

    double[][] sales = new double[10][5];

    Two-Dimensional Arrays

    (continued)

  • 8/3/2019 Programming Lecture 9

    57/77

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

    intExp1, intExp2 >= 0

    indexExp1 = row position

    indexExp2 = column position

    Accessing Array Elements

    A i A El

  • 8/3/2019 Programming Lecture 9

    58/77

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

    Accessing Array Elements

    (continued)

  • 8/3/2019 Programming Lecture 9

    59/77

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

    This statement declares and instantiates a two-

    dimensional array matrix of 20 rows and 15

    columns The value of the expression:

    matrix.lengthis 20, the number of rows

    Two-Dimensional Arrays and the

    Instance Variable length

    i i l A d h

  • 8/3/2019 Programming Lecture 9

    60/77

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

    Two-Dimensional Arrays and theInstance 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].length

    is 15, the number of columns in the first row

    matrix[1].length gives the number ofcolumns in the second row, which in this case is 15,

    and so on

  • 8/3/2019 Programming Lecture 9

    61/77

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

    Two-Dimensional Arrays: Special

    Cases

  • 8/3/2019 Programming Lecture 9

    62/77

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

    Create columns

    Two-Dimensional Arrays: Special

    Cases (continued)

  • 8/3/2019 Programming Lecture 9

    63/77

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

    Two-Dimensional Array Initialization

    During Declaration

  • 8/3/2019 Programming Lecture 9

    64/77

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

    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)

  • 8/3/2019 Programming Lecture 9

    65/77

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

    Two-Dimensional Array Initialization

    During Declaration (continued)

  • 8/3/2019 Programming Lecture 9

    66/77

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

    Two-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

    T Di i l A

  • 8/3/2019 Programming Lecture 9

    67/77

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

    Two-Dimensional Arrays:

    ProcessingInitialization

    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();

    }

    Two-Dimensional Arrays:

  • 8/3/2019 Programming Lecture 9

    68/77

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

    I

    nputfor (row = 0; row < matrix.length; row++)for (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)

  • 8/3/2019 Programming Lecture 9

    69/77

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

    Sum by Columnfor (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)

  • 8/3/2019 Programming Lecture 9

    70/77

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

    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])

    la

    rges

    t = ma

    trix[row][col

    ];System.out.println("The largest element of row "

    + (row + 1) + " = " + largest);

    }

    Two-Dimensional Arrays:

    Processing (continued)

  • 8/3/2019 Programming Lecture 9

    71/77

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

    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)

  • 8/3/2019 Programming Lecture 9

    72/77

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

    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

  • 8/3/2019 Programming Lecture 9

    73/77

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

    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;

  • 8/3/2019 Programming Lecture 9

    74/77

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

    Programming 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

  • 8/3/2019 Programming Lecture 9

    75/77

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

    Programming Example Solution:

    Text Processing An array of 26 representing the letters in the

    alphabet

    Three methods copyText

    characterCount

    writeTotal

    Value in appropriate index incrementedusing methods and depending on characterread from text

  • 8/3/2019 Programming Lecture 9

    76/77

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

    Chapter Summary

    Arrays

    Definition

    Uses Different Arrays

    One-dimensional

    Two-dimensional

    Multidimensional (n-dimensional) Arrays of objects

    Parallel arrays

  • 8/3/2019 Programming Lecture 9

    77/77

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

    Chapter Summary (continued)

    Declaring arrays

    Instantiating arrays

    Processing arrays

    Entire array

    Row processing

    Column processing

    Common operations and methodsperformed on arrays

    Manipulating data in arrays