1 Lecture 7 - Arrays Outline 4.6 4.7 4.8 4.9 4.10 Sorting Arrays Case Study: Computing Mean, Median and Mode Using Arrays Searching Arrays: Linear Search and Binary Search Multiple-Subscripted Arrays Thinking About Objects: Identifying a Class's Behaviors 2000 Prentice Hall, Inc. All rights reserved. 2 Sorting Arrays • Sorting data – Important computing application – Virtually every organization must sort some data • Massive amounts must be sorted • Bubble sort (sinking sort) – Several passes through the array – Successive pairs of elements are compared • If increasing order (or identical), no change • If decreasing order, elements exchanged – Repeat these steps for every element 2000 Prentice Hall, Inc. All rights reserved. 3 4.6 Sorting Arrays • Example: – – – – Original: 3 4 2 6 7 Pass 1: 3 2 4 6 7 Pass 2: 2 3 4 6 7 Small elements "bubble" to the top 2000 Prentice Hall, Inc. All rights reserved. 4 Case Study: Computing Mean, Median and Mode Using Arrays • Mean – Average • Median – Number in middle of sorted list – 1, 2, 3, 4, 5 (3 is median) • Mode – Number that occurs most often – 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode) 2000 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Fig. 4.17: fig04_17.cpp // This program introduces the topic of survey data analysis. // It computes the mean, median, and mode of the data. #include <iostream> 5 Outline 1. Function prototypes using std::cout; using std::endl; using std::ios; 1.1 Initialize array #include <iomanip> 2. Call functions mean, median, and mode using std::setw; using std::setiosflags; using std::setprecision; void void void void void mean( const int [], int ); median( int [], int ); mode( int [], int [], int ); bubbleSort( int[], int ); printArray( const int[], int ); int main() { const int responseSize = 99; int frequency[ 10 ] = { 0 }, response[ responseSize ] = { 6, 7, 8, 9, 8, 7, 8, 9, 7, 8, 9, 5, 9, 8, 7, 8, 6, 7, 8, 9, 3, 9, 8, 7, 7, 8, 9, 8, 9, 8, 9, 7, 6, 7, 8, 7, 8, 7, 9, 8, 7, 8, 9, 8, 9, 8, 9, 7, 2000 Prentice Hall, All rights reserved. 5, Inc. 6, 7, 2, 5, 3, 9, 4, 8, 7, 8, 8, 9, 5, 6, 9, 8, 7, 9, 2, 3, 4, 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 7, 8, 9, 6, 8, 7, 8, 9, 7, 8, 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 4, 5, 6, 1, 6, 5, 7, 8, 7 }; 6 Outline mean( response, responseSize ); median( response, responseSize ); mode( frequency, response, responseSize ); 3. Define function mean return 0; 3.1 Define function median } void mean( const int answer[], int arraySize ) { int total = 0; cout << "********\n Mean\n********\n"; for ( int j = 0; j < arraySize; j++ ) total += answer[ j ]; cout << << << << << << << << << "The mean is the average value of the data\n" "items. The mean is equal to the total of\n" "all the data items divided by the number\n" "of data items (" << arraySize "). The mean value for\nthis run is: " total << " / " << arraySize << " = " setiosflags( ios::fixed | ios::showpoint ) setprecision( 4 ) static_cast< double >( total ) / arraySize << "\n\n"; } void median( int answer[], int size ) { 2000 Prentice Hall, Inc. All rights reserved. cout << "\n********\n Median\n********\n" 68 << "The unsorted array of responses is"; 7 Outline 69 70 printArray( answer, size ); 71 bubbleSort( answer, size ); 72 cout << "\n\nThe sorted array is"; 73 printArray( answer, size ); 74 cout << "\n\nThe median is element " << size / 2 3.1 Define function median 75 << " of\nthe sorted " << size 76 << " element array.\nFor this run the median is " 77 << answer[ size / 2 ] << "\n\n"; 3.1.1 Sort Array 3.1.2 Print middle element 78 } 79 80 void mode( int freq[], int answer[], int size ) 81 { 82 int rating, largest = 0, modeValue = 0; 83 84 cout << "\n********\n Mode\n********\n"; 85 86 87 for ( rating = 1; rating <= 9; rating++ ) freq[ rating ] = 0; 88 89 90 91 92 93 94 for ( int j = 0; j < size; j++ ) ++freq[ answer[ j ] ]; Notice how the subscript in frequency[] is the value of an element in response[] (answer[]). cout << "Response"<< setw( 11 ) << "Frequency" << setw( 19 ) << "Histogram\n\n" << setw( 55 ) << "1 1 2 2\n" << setw( 56 ) Hall, Inc.0 All rights 95 2000 Prentice << "5 5 reserved. 0 5\n\n"; 3.2 Define function mode 3.2.1 Increase frequency[] depending on response[] 96 97 8 for ( rating = 1; rating <= 9; rating++ ) { 98 cout << setw( 8 ) << rating << setw( 11 ) 99 << freq[ rating ] << " "; 100 101 if ( freq[ rating ] > largest ) { 102 largest = freq[ rating ]; 103 modeValue = rating; 104 } 105 106 for ( int h = 1; h <= freq[ rating ]; h++ ) 107 cout << '*'; 108 109 110 Print stars depending on value of frequency[] cout << '\n'; } 111 112 cout << "The mode is the most frequent value.\n" 113 << "For this run the mode is " << modeValue 114 << " which occurred " << largest << " times." << endl; 115 } 116 117 void bubbleSort( int a[], int size ) 118 { 119 Outline int hold; 120 2000 Prentice Hall, Inc. All rights reserved. 3.3 Define bubbleSort 121 for ( int pass = 1; pass < size; pass++ ) 9 Outline 122 123 for ( int j = 0; j < size - 1; j++ ) 124 125 if ( a[ j ] > a[ j + 1 ] ) { 126 hold = a[ j ]; 127 a[ j ] = a[ j + 1 ]; 128 a[ j + 1 ] = hold; 129 } 130 } 131 132 void printArray( const int a[], int size ) 133 { 134 for ( int j = 0; j < size; j++ ) { 135 136 if ( j % 20 == 0 ) 137 cout << endl; 138 139 140 cout << setw( 2 ) << a[ j ]; } 141 } 2000 Prentice Hall, Inc. All rights reserved. 3.3 Define bubbleSort 3.3 Define printArray Bubble sort: if elements out of order, swap them. ******** Mean ******** The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items (99). The mean value for this run is: 681 / 99 = 6.8788 ******** Median ******** The unsorted 6 7 8 9 8 7 6 7 8 9 3 9 6 7 8 7 8 7 5 6 7 2 5 3 7 4 4 2 5 3 The sorted 1 2 2 2 3 5 6 6 6 6 7 7 7 7 7 8 8 8 8 8 9 9 9 9 9 array 8 9 8 8 7 8 9 8 9 9 4 6 8 7 5 array 3 3 3 6 6 6 7 7 7 8 8 8 9 9 9 of responses is 9 7 8 9 5 9 8 7 7 7 8 9 8 9 8 9 2 7 8 9 8 9 8 9 4 7 8 9 6 8 7 8 6 4 5 6 1 6 5 7 is 4 4 6 6 7 7 8 8 9 9 4 7 7 8 9 4 7 7 8 9 4 7 7 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 The median is element 49 of the sorted 99 element array. For this run the median is 7 2000 Prentice Hall, Inc. All rights reserved. 8 7 7 9 8 7 8 5 7 7 8 9 3 8 5 7 8 8 9 5 7 8 8 9 5 7 8 8 10 Outline 4. Program Output ******** Mode ******** Response 11 Outline Frequency Histogram 5 1 0 1 5 2 0 2 5 1 1 * 2 3 *** 3 4 **** 4 5 ***** 5 8 ******** 6 9 ********* 7 23 *********************** 8 27 *************************** 9 19 ******************* The mode is the most frequent value. For this run the mode is 8 which occurred 27 times. 2000 Prentice Hall, Inc. All rights reserved. Program Output 12 Just Do It! Write a program that asks a user to input as many floating point numbers as they’d like (up to 100). The program should ask each time whether the user would like to enter another number (y/n). After the user says no (“n”), the program should sort the numbers from largest to smallest and print the sorted list to the screen. Make sure you use a modified version of the bubbleSort function from the prior example. 2000 Prentice Hall, Inc. All rights reserved. 13 Pseudocode While the user wants to enter another number Get the user’s entry Store the number Keep track of how many elements have been entered Sort the entered numbers Display the sorted numbers 2000 Prentice Hall, Inc. All rights reserved. 14 Sample Solution // arraysort.cpp #include <iostream> using std::cout; using std::cin; using std::endl; void bubbleSort(float[], int); //declarations void swap(float& a, float& b); //-------------------------------------------------------------int main() { const int SIZE = 100; //maximum array elements float nums[SIZE]; int count = 0; //number of floats in array char ans = 'y'; do { cout << "Enter a number: "; cin >> nums[ count++ ]; cout << "Would you like to enter another (y/n)? "; cin >> ans; } while ( ans != 'n' ); bubbleSort(nums, count); for(int i=0; i<count; i++) cout << nums[i] << endl return 0; } 2000 Prentice Hall, Inc. All rights reserved. 15 Sample Solution void swap(float& a, float& b) { float temp; temp = a; a = b; b = temp; } void bubbleSort(float f[], int c) { int hold; for ( int j = 0; j < c - 1; j++ ) if ( f[ j ] < f[ j + 1 ] ) swap(f[ j ], f[ j + 1 ]); } 2000 Prentice Hall, Inc. All rights reserved. 16 Searching Arrays: Linear Search and Binary Search • Search array for a key value • Linear search – Compare each element of array with key value – Useful for small and unsorted arrays • Binary search – Can only be used on sorted arrays – Compares middle element with key • If equal, match found • If key < middle, repeat search through the first half of the array • If key > middle, repeat search through the last half of the array – Very fast; at most n steps, where 2^nn > # of elements • 30 element array takes at most 5 steps – 52 > 30 2000 Prentice Hall, Inc. All rights reserved. 17 Just Do It! Create a program that allows the user to input a number of integers, and then stores them in an int array. Write a function called maxint() that goes through the array, element by element, looking for the largest one. The function should take as arguments the address of the array and the number of elements in it, and return the index number of the largest element. The program should call this function and then display the largest element and its index number. 2000 Prentice Hall, Inc. All rights reserved. 18 Pseudocode Main While the user wants to enter another number Get the user’s entry Store the number Keep track of how many elements have been entered Determine the largest number entered (call the function) Display the largest number MaxInt function Search all numbers If the current number is larger than the previous largest Save the index of the current number Return the index of the largest number 2000 Prentice Hall, Inc. All rights reserved. 19 Sample Solution // arraymax.cpp #include <iostream> using std::cout; using std::cin; using std::endl; int maxint(int[], int); //declaration //-------------------------------------------------------------int main() { const int SIZE = 100; //maximum array elements int intarray[SIZE]; //array of ints int count = 0; //number of ints in array int intval; while(true) { cout << count << ". Enter an integer value (0 to end): "; cin >> intval; if(intval==0) break; intarray[count++] = intval; //set array element to value } //find largest element int bigdex = maxint(intarray, count); cout << "\nLargest element is number " << bigdex; cout << ", which contains " << intarray[bigdex] << endl; return 0; } 2000 Prentice Hall, Inc. All rights reserved. 20 Sample Solution (cont.) //-------------------------------------------------------------int maxint(int ia[], int c) //returns largest element { int bigdex = 0; //assume it's element 0 for(int j=1; j<c; j++) //if another is larger, if( ia[j] > ia[bigdex] ) //put its index in bigdex bigdex = j; return bigdex; } 2000 Prentice Hall, Inc. All rights reserved. 21 Multiple-Dimensional Arrays • So far we’ve only looked at arrays that have a single dimension – now we’ll look at multidimensional arrays • Let’s start with a two-dimensional array: 1 District1 District2 District3 District4 Month 2 3 $235 $354 $123 $221 $421 $397 $801 $892 $547 $241 $401 $932 • A 2-dimensional array is similar to a table • Example – salemon.cpp 2000 Prentice Hall, Inc. All rights reserved. 22 Multiple-Subscripted Arrays • Multiple subscripts - tables with rows, columns – Like matrices: specify row, then column. Row 0 Column 0 a[ 0 ][ 0 ] Column 1 a[ 0 ][ 1 ] Column 2 a[ 0 ][ 2 ] Column 3 a[ 0 ][ 3 ] Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ] Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ] Column subscript Array name Row subscript • Initialize int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 2 3 4 1 0 3 4 – Initializers grouped by row in braces int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 2000 Prentice Hall, Inc. All rights reserved. 23 Multiple-Dimensional Arrays (cont.) • Defining double sales[DISTRICTS][MONTHS]; double sales[YEARS][MONTHS][DISTRICTS]; • Accessing sales[d][m]; • Initializing double sales[4][3] = { {x, x, x}, {x, x, x}, {x, x, x}, {x, x, x} } • Example – saleinit.cpp 2000 Prentice Hall, Inc. All rights reserved. 24 Multiple-Subscripted Arrays • Referenced like normal cout << b[ 0 ][ 1 ]; – Will output the value of 0 – Cannot reference with commas cout << b( 0, 1 ); • Will try to call function b, causing a syntax error 2000 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Fig. 4.23: fig04_23.cpp // Double-subscripted array example #include <iostream> 25 Outline 1. Initialize variables using std::cout; using std::endl; using std::ios; 1.1 Define functions to take double scripted arrays #include <iomanip> using std::setw; using std::setiosflags; using std::setprecision; const int students = 3; const int exams = 4; 1.2 Initialize studentgrades[][] // number of students // number of exams int minimum( int [][ exams ], int, int ); int maximum( int [][ exams ], int, int ); double average( int [], int ); void printArray( int [][ exams ], int, int ); int main() { int studentGrades[ { { 77, 68, { 96, 87, { 70, 90, 2. Call functions minimum, maximum, and average Each row is a particular student, each column is the grades on the exam. students ][ exams ] = 86, 73 }, 89, 78 }, 86, 81 } }; cout << "The array is:\n"; printArray( studentGrades, students, exams ); cout << "\n\nLowest grade: " 2000 Prentice Hall, Inc. AllstudentGrades, rights reserved. << minimum( students, exams ) 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 << "\nHighest grade: " << maximum( studentGrades, students, exams ) << '\n'; for ( int person = 0; person < students; person++ ) cout << "The average grade for student " << person << " is " << setiosflags( ios::fixed | ios::showpoint ) << setprecision( 2 ) << average( studentGrades[ person ], exams ) << endl; return 0; } // Find the minimum grade int minimum( int grades[][ exams ], int pupils, int tests ) { int lowGrade = 100; for ( int i = 0; i < pupils; i++ ) for ( int j = 0; j < tests; j++ ) if ( grades[ i ][ j ] < lowGrade ) lowGrade = grades[ i ][ j ]; return lowGrade; } // Find the maximum grade int maximum( int grades[][ exams ], int pupils, int tests ) { int highGrade = 0; 2000 Allirights reserved. i++ ) forPrentice ( intHall, i Inc. = 0; < pupils; 26 Outline 2. Call functions minimum, maximum, and average 3. Define functions 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 27 for ( int j = 0; j < tests; j++ ) if ( grades[ i ][ j ] > highGrade ) highGrade = grades[ i ][ j ]; return highGrade; } // Determine the average grade for a particular student double average( int setOfGrades[], int tests ) { int total = 0; for ( int i = 0; i < tests; i++ ) total += setOfGrades[ i ]; return static_cast< double >( total ) / tests; } // Print the array void printArray( int grades[][ exams ], int pupils, int tests ) { cout << " [0] [1] [2] [3]"; for ( int i = 0; i < pupils; i++ ) { cout << "\nstudentGrades[" << i << "] "; for ( int j = 0; j < tests; j++ ) cout << setiosflags( ios::left ) << setw( 5 ) << grades[ i ][ j ]; } } 2000 Prentice Hall, Inc. All rights reserved. Outline 3. Define functions The array is: [0] studentGrades[0] 77 studentGrades[1] 96 studentGrades[2] 70 [1] 68 87 90 [2] 86 89 86 [3] 73 78 81 Lowest grade: 68 Highest grade: 96 The average grade for student 0 is 76.00 The average grade for student 1 is 87.50 The average grade for student 2 is 81.75 2000 Prentice Hall, Inc. All rights reserved. 28 Outline Program Output 29 Just Do It! Create a program that creates a deck of cards, shuffles the deck, and deals the 52 cards to each of 4 players. Be sure to deal the cards one at a time to each player – DON’T give one player 13, then the next 13, etc. This problem may end up being more complicated than it initially sounds. Think carefully about how to store the deck of cards and then have a separate storage for the cards in the player’s hands. Feel free to use functions! Hints: Think multi-dimensional arrays. Use rand to shuffle the deck. Use ints to represent the suits and values of the cards. A single card requires two values to represent it. 2000 Prentice Hall, Inc. All rights reserved. 30 Pseudocode Create a deck of cards Shuffle the deck For each card in the deck Give the card to the next player For each player For each card in the player’s hand Display the card Go to the next line before displaying the next hand 2000 Prentice Hall, Inc. All rights reserved. 31 Sample Solution // bridge.cpp – deals four bridge hands #include <iostream> #include <cstdlib> //for srand(), rand() #include <ctime> //for time for srand() using std::cout; using std::cin; using std::endl; // card suits const int clubs = 0; const int hearts = 1; const int spades = 2; const int diamonds = 3; //from 2 to 10 are integers without names const int jack = 11; const int queen = 12; const int king = 13; const int ace = 14; const int PLAYERS = 4; const int CARDS_IN_HAND = 13; const int CARDS_IN_DECK = 52; const int VALUE = 0; const int SUIT = 1; //-------------------------------------------------------------// function display_card prototype void display_card(int[]); 2000 Prentice Hall, Inc. All rights reserved. 32 Sample Solution (cont.) //////////////////////////////////////////////////////////////// int main() { int count, j, k, tempVal, tempSuit; card deck[CARDS_IN_DECK][2]; card player_hands[PLAYERS][CARDS_IN_HAND][2]; cout << endl; for(j=0; j<CARDS_IN_DECK; j++) //make an ordered deck { int num = (j % CARDS_IN_HAND) + 2; //cycles through 2 to 14, 4 times int su = j / CARDS_IN_HAND; //cycles through 0 to 3, 13 times deck[j][VALUE] = num; //set card deck[j][SUIT] = su; } //shuffle the deck srand( time(NULL) ); //seed random numbers with time for(j=0; j<CARDS_IN_DECK; j++) //for each card in the deck, { k = rand() % CARDS_IN_DECK; //pick another card at random and swap tempVal = deck[j][VALUE]; tempSuit = deck[j][SUIT]; deck[j][VALUE] = deck[k][VALUE]; deck[j][SUIT] = deck[k][SUIT]; deck[k][VALUE] = tempVal; deck[k][SUIT] = tempSuit; } 2000 Prentice Hall, Inc. All rights reserved. 33 Sample Solution (cont.) count = 0; for(j=0; j<CARDS_IN_DECK; j++) //deal four hands of 13 cards { player_hands[j%4][j/4][VALUE] = deck[j][VALUE]; player_hands[j%4][j/4][SUIT] = deck[j][SUIT]; } for(j=0; j<PLAYERS; j++) //display the player hands { cout << "\nPlayer " << j+1 << " holds: "; for(k=0; k<CARDS_IN_HAND; k++) { display_card(player_hands[j][k]); cout << ", "; } cout << endl; } return 0; } //end main 2000 Prentice Hall, Inc. All rights reserved. 34 Sample Solution (cont.) //-------------------------------------------------------------// display_card function definition void display_card(int aCard[]) //display the card { if( aCard[VALUE] >= 2 && aCard[VALUE] <= 10 ) cout << aCard[VALUE]; else switch(aCard[VALUE]) { case jack: cout << "J"; break; case queen: cout << "Q"; break; case king: cout << "K"; break; case ace: cout << "A"; break; } switch(aCard[SUIT]) { case clubs: cout << static_cast<char>(5); break; case hearts: cout << static_cast<char>(3); break; case spades: cout << static_cast<char>(6); break; case diamonds: cout << static_cast<char>(4); break; } } 2000 Prentice Hall, Inc. All rights reserved. 35 Thinking (some more) About Objects • Previous chapters – Chapter 2 - identified classes – Chapter 3 - determined many attributes of our classes • This chapter – Determine operations (behaviors) • Chapter 5 – Focus on interactions between classes 2000 Prentice Hall, Inc. All rights reserved. 36 Class Operations • Class operations – Service class provides to clients • Radio - setting station, volume – Objects usually do not perform operations spontaneously • Operations invoked by sending object (client object) • Sends message to receiving object (server object) • Requests object perform specific operation • Deriving operations – Examine problem statement for verbs and verb phrases – Relate phrases to particular classes 2000 Prentice Hall, Inc. All rights reserved. 37 Class Operations (II) Cla ss Verb p hra ses Elevator moves, arrives at a floor, resets the elevator button, sounds the elevator bell, signals its arrival to a floor, opens its door, closes its door Clock ticks every second Scheduler randomly schedules times, creates a person, tells a person to step onto a floor, verifies that a floor is unoccupied, delays creating a person by one second Person steps onto floor, presses floor button, presses elevator button, enters elevator, exits elevator Floor resets floor button, turns off light, turns on light FloorButton summons elevator ElevatorButton signals elevator to move Door (opening of door) signals person to exit elevator, (opening of door) signals person to enter elevator Bell none in problem statement Light none in problem statement Building none in problem statement 2000 Prentice Hall, Inc. All rights reserved. 38 Creating Class Operations • Creating operations – Examine verb phrase "moves" verb is listed with Elevator – – Should "moves" be an operation? No message tells elevator to move • Moves in response to a button, on condition that door is closed • "Moves" should not be an operation – "Arrives at floor" should not be an operation • Elevator itself decides when to arrive, based on time – "resets elevator button" - implies elevator sends message to elevator button, telling it to reset • ElevatorButton needs an operation to provide this service to the elevator 2000 Prentice Hall, Inc. All rights reserved. 39 Creating Class Operations (II) • Format – Write operation name in bottom compartment in class diagram – Write operations as function names, include return type, parameters resetButton() : void • Function takes no parameters, returns nothing • Other verbs – Bell - provides service of ringing – Floor - signal arrival of elevator – Door - open and close 2000 Prentice Hall, Inc. All rights reserved. 40 Creating Class Operations (III) Elevator currentFloor : int = 1 direction : enum = up capacity : int = 1 arrivalTime : int moving : bool = false processTime( time : int ) : void personEnters( ) : void personExits( ) : void summonElevator( ) : void prepareToLeave( ) : void Scheduler Clock Door time : int = 0 open : bool = false getTime( ) : int tick( ) : void openDoor( ) : void closeDoor( ) : void Floor Bell occupied : bool = false elevatorArrived( ) : void isOccupied( ) : bool <none yet> ringBell( ) : void FloorButton floor1ArrivalTime : int floor2ArrivalTime : int pressed : bool = false processTime( time : int ) : void pressButton( ) : void resetButton( ) : void Light on : bool = false turnOff( ) : void turnOn( ) : void Person ID : int ElevatorButton pressed : bool = false stepOntoFloor( ) : void exitElevator( ) : void enterElevator( ) : void 2000 Prentice Hall, Inc. All rights reserved. resetButton( ) : void pressButton( ) : void Building <none yet> runSimulation( ) : void 41 Class Clock, Building • Class Clock – Has phrase "ticks every second" – "Getting the time" is an operation clock provides • Is the ticking also an operation? • Look at how simulation works • Building, once per second, will – – – – Get time from clock Give time to scheduler Give time to elevator Building has full responsibility for running simulation, therefore it must increment clock – getTime and tick therefore operations of Clock – processTime operation of Scheduler and Elevator 2000 Prentice Hall, Inc. All rights reserved. 42 Class Scheduler • Class Scheduler – "randomly schedules times", "delays creating a person by one second" – Scheduler performs these actions itself, does not provide service to clients – "create person" - special case • A Person object cannot respond to a create message because it does not yet exist • Creation left to implementation details, not an operation of a class • More Chapter 7 – "tells a person to step onto a floor" - class Person should have a function that the scheduler can invoke • stepOntoFloor - operation of class Person 2000 Prentice Hall, Inc. All rights reserved. 43 Class Person • More verb phrases – "verifies a floor is unoccupied" - class Floor needs a service to let other objects know if a floor is occupied or not • isOccupied returns true or false • Class Person – "presses floor button", "presses elevator button" • Place operation pressButton under classes FloorButton and ElevatorButton – "enter elevator", "exit elevator" - suggests class Elevator needs operations to correspond to these actions • Discover what, if any, actions operations perform when concentrate on implementation 2000 Prentice Hall, Inc. All rights reserved. 44 Class Floor, FloorButton, ElevatorButton • Class Floor – "resets floor button" - resetButton operation – "turns off light", "turns on light" - turnOff and turnOn in class Light • Class FloorButton and ElevatorButton – "summons elevator" - summonElevator operation in class Elevator – "signals elevator to move" - elevator needs to provide a "move" service • Before it can move, must close door • prepareToLeave operation (performs necessary actions before moving) in class Elevator 2000 Prentice Hall, Inc. All rights reserved. 45 Class Door • Class Door – Phrases imply door sends message to person to tell it to exit or enter elevator – exitElevator and enterElevator in class Person • Notes – We do not overly concern ourselves with parameters or return types – Only want a basic understanding of each class – As we continue design, number of operations may vary • New operations needed • Some current operations unnecessary 2000 Prentice Hall, Inc. All rights reserved. 46 Sequence Diagrams • Sequence Diagram – Model our "Simulation loop" – Focuses on how messages are sent between objects over time • Format – Each object represented by a rectangle at top of diagram • Name inside rectangle (objectName) – Lifeline - dashed vertical line, represents progression of time • Actions occur along lifeline in chronological order, top to bottom – Line with arrowhead - message between objects • • • • Invokes corresponding operation in receiving object Arrowhead points to lifeline of receiving object Name of message above message line, includes parameters Parameter name followed by colon and parameter type 2000 Prentice Hall, Inc. All rights reserved. 47 Sequence Diagrams (II) : Building : Clock : Scheduler tick( ) {currentTime < totalTime} getTime( ) time processTime( currentTime : int ) processTime( currentTime : int ) 2000 Prentice Hall, Inc. All rights reserved. : Elevator 48 Sequence Diagrams (III) • Flow of control – If object returns flow of control or returns a value, return message (dashed line with arrowhead) goes back to original object • Clock object returns time in response to getTime message received from Building object • Activations – Rectangles along lifelines - represent duration of an activity • Height corresponds to duration • Timing constraint – In our diagram, text to far left – While currentTime < totalTime objects keep sending messages as in the diagram 2000 Prentice Hall, Inc. All rights reserved. building : Building 49 scheduler : Scheduler processTime( time ) floor1 : Floor floor2 : Floor isOccupied( ) : bool bool converge The two lifelines [occupied = true] scheduler second floor same way as the first [occupied =handles false] When returns control to building createfinished,: Person personArrives( ) building sends processTime message to scheduler delayArrival( floor1 ) scheduleArrival( floor1 ) scheduler decides whether to create a new person Can only create a new person if floor unoccupied Checks by sending isOccupied floor floor1 returns true or false message toisOccupied( ) : bool object scheduler's lifeline splits - conditional executionbool of activities. Condition supplied for each lifeline. After new Person [occupied = false] object created, it steps on first floor create Person If true - scheduler calls Person delayArrival object :sends personArrives message to personArrives( ) [occupied = true] Not an operation - not invokedfloor1 by another object object If false - scheduler creates new Person delayArrival( floor2 ) scheduler schedules new arrival for floor1 scheduleArrival( floor2 ) object calls its own scheduleArrival function (not an When new objects created, rectangle corresponds to operation) time. Message "create" sent from one object to another (arrowhead points to new object). 2000 Prentice Hall, Inc. All rights reserved. 50 Conclusion • Discussed operations of classes – Introduced sequence diagrams to illustrate operations • Chapter 5 – Examine how objects interact with each other 2000 Prentice Hall, Inc. All rights reserved.