1. Trang chủ
  2. » Thể loại khác

Java - profthinh ď jhtp5_07

70 228 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Chapter - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 References and Reference Parameters 7.6 Passing Arrays to Methods 7.7 Sorting Arrays 7.8 Searching Arrays: Linear Search and Binary Search 7.9 Multidimensional Arrays 7.10 (Optional Case Study) Thinking About Objects: Collaboration Among Objects 2003 Prentice Hall, Inc All rights reserved 7.1 Introduction • Arrays – Data structures – Related data items of same type – Remain same size once created • Fixed-length entries  2003 Prentice Hall, Inc All rights reserved 7.2 Arrays • Array – Group of variables • Have same type – Reference type  2003 Prentice Hall, Inc All rights reserved Name of array (note that all elements of this array have the same name, c) Index (or subscript) of the element in array c c[ ] -45 c[ ] c[ ] c[ ] 72 c[ ] 1543 c[ ] -89 c[ ] c[ ] 62 c[ ] -3 c[ ] c[ 10 ] 6453 c[ 11 ] 78 Fig 7.1 A 12-element array  2003 Prentice Hall, Inc All rights reserved 7.2 Arrays (cont.) • Index – Also called subscript – Position number in square brackets – Must be positive integer or integer expression a = 5; b = 6; c[ a + b ] += 2; • Adds to c[ 11 ]  2003 Prentice Hall, Inc All rights reserved 7.2 Arrays (cont.) • Examine array c – c is the array name – c.length accesses array c’s length – c has 12 elements ( c[0], c[1], … c[11] ) • The value of c[0] is –45  2003 Prentice Hall, Inc All rights reserved 7.3 Declaring and Creating Arrays • Declaring and Creating arrays – Arrays are objects that occupy memory – Created dynamically with keyword new int c[] = new int[ 12 ]; – Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create array • We can create arrays of objects too String b[] = new String[ 100 ];  2003 Prentice Hall, Inc All rights reserved 7.4 Examples Using Arrays • • • • Declaring arrays Creating arrays Initializing arrays Manipulating array elements  2003 Prentice Hall, Inc All rights reserved 7.4 Examples Using Arrays (Cont.) • Creating and initializing an array – Declare array – Create array – Initialize array elements  2003 Prentice Hall, Inc All rights reserved 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Outline // Fig 7.2: InitArray.java // Creating an array import javax.swing.*; InitArray.java Create 10 ints for array; each Declare array asinitialized an int is to by defaultLine public static void main( String args[] ) of ints array Declare array as an { int array[]; // declare reference to an array array of ints array.length returns array = new int[ 10 ]; // create array length of array Line 11 public class InitArray { String output = "Index\tValue\n"; // append each array element's value to String output for ( int counter = 0; counter < array.length; counter++ ) output += counter + "\t" + array[ counter ] + "\n"; JTextArea outputArea = new JTextArea(); outputArea.setText( output ); JOptionPane.showMessageDialog( null, outputArea, "Initializing an Array of int Values", JOptionPane.INFORMATION_MESSAGE ); array[counter] System.exit( ); } // end main Create 10 ints for array; each int is initialized to by default Line 16 array.length returns length of array returns Line int 17 associated with index in array array[counter] returns int associated with index in array } // end class InitArray  2003 Prentice Hall, Inc All rights reserved 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 Outline // build output string output = "The array is:\n"; buildString(); // call methods minimum and maximum output += "\n\nLowest grade: " + minimum() + "\nHighest grade: " + maximum() + "\n"; // call method average to calculate each student's average for ( int counter = 0; counter < students; counter++ ) output += "\nAverage for student " + counter + " is " + average( grades[ counter ] ); // pass one row of array DoubleArray.jav Determine a minimum and maximum for all student Lines 31-32 Determine minimum and maximum for all student grades // change outputArea's display font outputArea.setFont( new Font( "Monospaced", Font.PLAIN, 12 ) ); // place output string in outputArea outputArea.setText( output ); } // end method init Lines 35-37 Determine average for each student Determine average for each student // find minimum grade public int minimum() { // assume first element of grades array is smallest int lowGrade = grades[ ][ ];  2003 Prentice Hall, Inc All rights reserved 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 // loop through rows of grades array for ( int row = 0; row < students; row++ ) // loop through columns of current row for ( int column = 0; column < exams; column++ Use a nested loop to search for lowest grade in series DoubleArray.jav ) a // if grade is less than lowGrade, assign it to lowGrade if ( grades[ row ][ column ] < lowGrade ) lowGrade = grades[ row ][ column ]; return lowGrade; // return lowest grade } // end method minimum Outline Use a nested loop to search for highest grade in series // find maximum grade public int maximum() { // assume first element of grades array is largest int highGrade = grades[ ][ ]; Lines 54-61 Use a nested loop to search for lowest grade in series Lines 74-81 Use a nested loop to search for highest grade in series // loop through rows of grades array for ( int row = 0; row < students; row++ ) // loop through columns of current row for ( int column = 0; column < exams; column++ ) // if grade is greater than highGrade, assign it to highGrade if ( grades[ row ][ column ] > highGrade ) highGrade = grades[ row ][ column ];  2003 Prentice Hall, Inc All rights reserved 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 return highGrade; Outline // return highest grade DoubleArray.jav Method average takes array of student test results asaparameter set of grades) } // end method maximum // determine average grade for particular student (or public double average( int setOfGrades[] ) { int total = 0; // initialize total Calculate // sum grades for one student for ( int count = 0; count < setOfGrades.length; total += setOfGrades[ count ]; // return average of grades return ( double ) total / setOfGrades.length; } // end method average // build output string public void buildString() { output += " "; Line 88 Method average sum of array elements takes array of student test results as count++ ) parameter Divide by number of elements to get average Lines 93-94 Calculate sum of array elements // used to align column heads Line 97 Divide by number of elements to get average // create column heads for ( int counter = 0; counter < exams; counter++ ) output += "[" + counter + "] ";  2003 Prentice Hall, Inc All rights reserved 109 110 111 112 113 114 115 116 117 118 119 120 // create rows/columns of text representing array grades for ( int row = 0; row < students; row++ ) { output += "\ngrades[" + row + "] "; for ( int column = 0; column < exams; column++ ) output += grades[ row ][ column ] + " "; Outline DoubleArray.jav a } } // end method buildString } // end class DoubleArray  2003 Prentice Hall, Inc All rights reserved 7.10 (Optional Case Study) Thinking 60 About Objects: Collaboration Among Objects • Collaborations – When objects communicate to accomplish task • Accomplished by invoking operations (methods) – One object sends a message to another object – In 6.15, we extracted verb phrases from problem statement • Verb phrases exhibit behaviors of classes • “The elevator resets its button” – Elevator object sends resetButton message to ElevatorButton object – Elevator collaborates with ElevatorButton  2003 Prentice Hall, Inc All rights reserved 61 Class Elevator Verb phrases resets elevator button, rings elevator bell, signals its arrival, signals its departure, opens its door, closes its door  turns off light, turns on light, resets floor button ElevatorShaft presses floor button, presses elevator button, rides Person elevator, enters elevator, exits elevator summons (requests) elevator FloorButton ElevatorButton signals elevator to move to opposite floor signals person to enter elevator (by opening) FloorDoor signals person to exit elevator (by opening), opens floor ElevatorDoor door, closes floor door Fig 7.16 Verb phrases for each class exhibiting behaviors in simulation  2003 Prentice Hall, Inc All rights reserved 62 An object of class Elevator Sends the message To an object of class resetButton ElevatorButton ringBell Bell elevatorArrived ElevatorShaft elevatorDeparted ElevatorShaft openDoor ElevatorDoor closeDoor ElevatorDoor ElevatorShaft resetButton FloorButton turnOnLight Light turnOffLight Light Person pressButton FloorButton, ElevatorButton enterElevator Elevator exitElevator Elevator FloorButton requestElevator Elevator ElevatorButton moveElevator Elevator FloorDoor doorOpened Person doorClosed Person ElevatorDoor doorOpened Person doorClosed Person openDoor FloorDoor closeDoor FloorDoor Fig 7.17 Collaborations in the elevator system  2003 Prentice Hall, Inc All rights reserved 63 7.10 Thinking About Objects (cont.) • Collaboration diagram (UML) – Type of interaction diagram • The other is sequence diagram, discussed in Chapter 16 – Models collaborations in system  2003 Prentice Hall, Inc All rights reserved 64 7.10 Thinking About Objects (cont.) • Collaboration-diagram notation – Objects are written in form objectName : ClassName • Disregard objectName only when concerned about class – Solid lines connect collaborating objects – Arrows represent messages • Indicates direction of collaboration • Points toward object receiving message • Can be implemented as a methods (synchronous calls) in Java – Message names appear next to arrows  2003 Prentice Hall, Inc All rights reserved 65 pressButton( ) : Person : FloorButton Fig 7.18 Collaboration diagram of a person pressing a floor button  2003 Prentice Hall, Inc All rights reserved 66 7.10 Thinking About Objects (cont.) • Collaboration-diagram sequence of messages – Shows in what order objects send messages – For diagrams modeling several collaborations – Progresses in numerical order • Least to greatest • Numbering starts with message • Follows a nested structure – Message 1.1 is first message nested in message – Message 3.2 is the second message nested in message – Message can be passed only when all nested messages from previous message have been passed  2003 Prentice Hall, Inc All rights reserved 67 3.1 : openDoor( ) 3.1.1 doorOpened( ) : FloorDoor 4.1 : resetButton( ) 4.2 : turnOnLight( ) : ElevatorShaft : FloorButton : Light 4: elevatorArrived( ) : Person passenger : Person : Elevator 3.2.1 : exitElevator( ) 3.2 : doorOpened( ) 3.1.1.1 : enterElevator( ) 1: resetButton( ) : ElevatorButton 2: ringBell( ) 3: openDoor( ) : Bell : ElevatorDoor ig 7.19 Collaboration diagram for passengers exiting and entering the elevator 2003 Prentice Hall, Inc All rights reserved 68 7.10 Thinking About Objects (cont.) • Collaborations in Fig 7.19 – Message • Elevator sends resetButton to ElevatorButton – Message • Elevator sends ringBell to Bell – Message • Elevator sends openDoor to ElevatorDoor – Message 3.1 • ElevatorDoor sends openDoor to FloorDoor – Message 3.1.1 • FloorDoor sends doorOpened to waitingPassenger – Message 3.1.1.1 • waitingPassenger sends enterElevator to Elevator  2003 Prentice Hall, Inc All rights reserved 69 7.10 Thinking About Objects (cont.) • Collaborations in Fig 7.20 (continued) – Message 3.2 • ElevatorDoor sends doorOpened to ridingPassenger – Message 3.2.1 • Person sends exitElevator to Elevator – Message • Elevator sends elevatorArrived to ElevatorShaft – Message 4.1 • ElevatorShaft sends resetButton to FloorButton – Message 4.2 • ElevatorShaft sends turnOnLight to Light  2003 Prentice Hall, Inc All rights reserved 70 7.10 Thinking About Objects (cont.) • Unfortunately, this design has a problem – waitingPassenger enters Elevator before ridingPassenger exits • We fix this in Section 16.11 • We modify this diagram in Section 11.9 (event handling)  2003 Prentice Hall, Inc All rights reserved ... ways to pass arguments to methods – Pass-by-value • Copy of argument’s value is passed to called method • In Java, every primitive is pass-by-value – Pass-by-reference • • • • Caller gives called... Called method can manipulate this data Improved performance over pass-by-value In Java, every object is pass-by-reference – In Java, arrays are objects • Therefore, arrays are passed to methods... (or subscript) of the element in array c c[ ] -4 5 c[ ] c[ ] c[ ] 72 c[ ] 1543 c[ ] -8 9 c[ ] c[ ] 62 c[ ] -3 c[ ] c[ 10 ] 6453 c[ 11 ] 78 Fig 7.1 A 12-element array  2003 Prentice Hall, Inc All

Ngày đăng: 11/12/2017, 19:43

Xem thêm:

TỪ KHÓA LIÊN QUAN

Mục lục

    7.3 Declaring and Creating Arrays

    InitArray.java Line 9 Declare array as an array of ints Line 11 Create 10 ints for array; each int is initialized to 0 by default Line 16 array.length returns length of array Line 17 array[counter] returns int associated with index in array

    InitArray.java Each int is initialized to 0 by default

    InitArray.java Line 11 Declare array as an array of ints Line 11 Compiler uses initializer list to allocate array

    InitArray.java Each array element corresponds to element in initializer list

    InitArray.java Line 10 Declare array as an array of ints Line 12 Create 10 ints for array Line 16 Use array index to assign array value

    SumArray.java Line 9 Declare array with initializer list Lines 13-14 Sum all array values

    Histogram.java Line 9 Declare array with initializer list Line 19 For each array element, print associated number of asterisks

    RollDie.java Line 9 Declare frequency as array of 7 ints Lines 12-13 Generate 6000 random integers in range 1-6 Line 13 Increment frequency values at index associated with random number

    StudentPoll.java Lines 9-11 Declare responses as array to store 40 responses Line 12 Declare frequency as array of 11 int and ignore the first element Lines 16-17 For each response, increment frequency values at index associated with that response

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN

w