JavaHTP6e_07
99 Pages

JavaHTP6e_07

Course Number: COSC 2103, Fall 2009

College/University: LeTourneau

Word Count: 6889

Rating:

Document Preview

1 7 Arrays 2005 Pearson Education, Inc. All rights reserved. 2 Now go, write it before them in a table, and note it in a book. -- Isaiah 30:8 To go beyond is as wrong as to fall short. -- Confucius Begin at the beginning,... and go on till you come to the end: then stop. -- Lewis Carroll 2005 Pearson Education, Inc. All rights reserved. 3 OBJECTIVES In this chapter you will learn: What arrays are. To...

Unformatted Document Excerpt
Coursehero >> Texas >> LeTourneau >> COSC 2103

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

2005 1 7 Arrays Pearson Education, Inc. All rights reserved. 2 Now go, write it before them in a table, and note it in a book. -- Isaiah 30:8 To go beyond is as wrong as to fall short. -- Confucius Begin at the beginning,... and go on till you come to the end: then stop. -- Lewis Carroll 2005 Pearson Education, Inc. All rights reserved. 3 OBJECTIVES In this chapter you will learn: What arrays are. To use arrays to store data in and retrieve data from lists and tables of values. To declare an array, initialize an array and refer to individual elements of an array. To use the enhanced for statement to iterate through arrays. To pass arrays to methods. To declare and manipulate multidimensional arrays. To write methods that use variable-length argument lists. To read command-line arguments into a program. 2005 Pearson Education, Inc. All rights reserved. 4 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 7.11 7.12 7.13 7.14 7.15 Introduction Arrays Declaring and Creating Arrays Examples Using Arrays Case Study: Card Shuffling and Dealing Simulation Enhanced for Statement Passing Arrays to Methods Case Study: Class GradeBook Using an Array to Store Grades Multidimensional Arrays Case Study: Class GradeBook Using a Two-Dimensional Array Variable-Length Argument Lists Using Command-Line Arguments (Optional) GUI and Graphics Case Study: Drawing Arcs (Optional) Software Engineering Case Study: Collaboration Among Objects Wrap-Up 2005 Pearson Education, Inc. All rights reserved. 5 7.1 Introduction Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries 2005 Pearson Education, Inc. All rights reserved. 6 7.2 Arrays Array Group of variables Have same type Reference type 2005 Pearson Education, Inc. All rights reserved. 7 Fig. 7.1 | A 12-element array. 2005 Pearson Education, Inc. All rights reserved. 8 7.2 Arrays (Cont.) Index Also called subscript Position number in square brackets Must be positive integer or integer expression First element has index zero a = 5; b = 6; c[ a + b ] += 2; Adds 2 to c[ 11 ] 2005 Pearson Education, Inc. All rights reserved. 9 Common Programming Error 7.1 Using a value of type long as an array index results in a compilation error. An index must be an int value or a value of a type that can be promoted to int--namely, byte , shor t or char , but not long . 2005 Pearson Education, Inc. All rights reserved. 10 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 2005 Pearson Education, Inc. All rights reserved. 11 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[ 1 00 ]; 2005 Pearson Education, Inc. All rights reserved. 12 Common Programming Error 7.2 In an array declaration, specifying the number of elements in the square brackets of the declaration (e.g., int c[ 12 ];) is a syntax error. 2005 Pearson Education, Inc. All rights reserved. 13 Good Programming Practice 7.1 For readability, declare only one variable per declaration. Keep each declaration on a separate line, and include a comment describing the variable being declared. 2005 Pearson Education, Inc. All rights reserved. 14 Common Programming Error 7.3 Declaring multiple array variables in a single declaration can lead to subtle errors. Consider the declaration int[] a, b, c; . If a , b and c should be declared as array variables, then this declaration is correct--placing square brackets directly following the type indicates that all the identifiers in the declaration are array variables. However, if only a is intended to be an array variable, and b and c are intended to be individual int variables, then this declaration is incorrect--the declaration int a[], b, c; would achieve the desired result. 2005 Pearson Education, Inc. All rights reserved. 15 7.4 Examples Using Arrays Declaring arrays Creating arrays Initializing arrays Manipulating array elements 2005 Pearson Education, Inc. All rights reserved. 16 7.4 Examples Using Arrays Creating and initializing an array Declare array Create array Initialize array elements 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // Fig. 7.2: InitArray.java // Creating an array. public class InitArray Declare array as { array public static void main( String args[] ) of ints { int array[]; // declare array named array Outline an Create 10 ints for array; each int is initialized to 0 by default InitArray java . Line 8 Declare array as an array of ints Line 1 0 Create 1 0 ints f or array; each int is initialized to 0 by default Line 1 5 array length . returns length of array Line 1 6 array[counter] returns int associated with index in array Program output 17 array = new int[ 10 ]; // create the space for array array.length returns length of array System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); } // end main } // end class InitArray Index Value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 Each int is initialized to 0 by default array[counter] returns int associated with index in array 2005 Pearson Education, Inc. All rights reserved. 18 7.4 Examples Using Arrays (Cont.) Using an array initializer Use initializer list Items enclosed in braces ({}) Items in list separated by commas int n[] = { 1 0, 20, 30, 40, 50 }; Creates a five-element array Index values of 0, 1, 2, 3, 4 Do not need keyword new 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // Fig. 7.3: InitArray.java // Initializing the elements of an array with an array initializer. public class InitArray array of ints { public static void main( String args[] ) Compiler uses initializer { to allocate array // initializer list specifies the value for each element int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); } // end main } // end class InitArray Declare array as an Outline list InitArray java . Line 9 Declare array as an array of ints Line 9 Compiler uses initializer list to allocate array 19 Index Value 0 32 1 27 2 64 3 18 4 95 5 14 6 90 7 70 8 60 9 37 Program output 2005 Pearson Education, Inc. All rights reserved. 20 7.4 Examples Using Arrays (Cont.) Calculating a value to store in each array element Initialize elements of 10-element array to even integers 2005 Pearson Education, 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 // Fig. 7.4: InitArray.java // Calculating values to be placed into elements of an array. Outline 21 public class InitArray Declare constant variable ARRAY_LENGTH { using the final modifier public static void main( String args[] ) InitArray java . { final int ARRAY_LENGTH = 10; // declare constant Declare and create array Line 8 int array[] = new int[ ARRAY_LENGTH ]; // create array // calculate value for each array element for ( int counter = 0; counter < array.length; counter++ ) array[ counter ] = 2 + 2 * counter; System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); Use array index to } // end main assign array value } // end class InitArray that contains 10 ints Declare constant variable Line 9 Declare and create array that contains 1 0 ints Line 1 3 Use array index to assign array Index Value 0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 16 8 18 9 20 Program output 2005 Pearson Education, Inc. All rights reserved. 22 Good Programming Practice 7.2 Constant variables also are called named constants or read-only variables. Such variables often make programs more readable than programs that use literal values (e.g., 10)--a named constant such as ARRAY_LENGTH clearly indicates its purpose, whereas a literal value could have different meanings based on the context in which it is used. 2005 Pearson Education, Inc. All rights reserved. 23 Common Programming Error 7.4 Assigning a value to a constant after the variable has been initialized is a compilation error. 2005 Pearson Education, Inc. All rights reserved. 24 Common Programming Error 7.5 Attempting to use a constant before it is initialized is a compilation error. 2005 Pearson Education, Inc. All rights reserved. 25 7.4 Examples Using Arrays (Cont.) Summing the elements of an array Array elements can represent a series of values We can sum these values 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 // Fig. 7.5: SumArray.java // Computing the sum of the elements of an array. public class SumArray { public static void main( String args[] ) { int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; Declare array with initializer list Outline SumArray java . Line 8 Declare array with initializer list 26 11 // add each element's value to total 12 for ( int counter = 0; counter < array.length; counter++ ) 13 total += array[ counter ]; 14 16 } // end main 17 } // end class SumArray Total of array elements: 849 Lines 121 3 Sum all array values Sum all array values 15 System.out.printf( "Total of array elements: %d\n", total ); Program output 2005 Pearson Education, Inc. All rights reserved. 27 7.4 Examples Using Arrays (Cont.) Using bar charts to display array data graphically Present data in graphical manner E.g., bar chart Examine the distribution of grades 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 // Fig. 7.6: BarChart.java // Bar chart printing program. public class BarChart Outline Declare array with initializer list BarChar t.jav a 28 { public static void main( String args[] ) { int array[] = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 }; 9 10 System.out.println( "Grade distribution:" ); 11 12 // for each array element, output a bar of the chart 13 for ( int counter = 0; counter < array.length; counter++ ) 14 { 15 // output bar label ( "0009: ", ..., "9099: ", "100: " ) 16 if ( counter == 10 ) 17 System.out.printf( "%5d: ", 100 ); 18 else 19 System.out.printf( "%02d%02d: ", 20 counter * 10, counter * 10 + 9 ); 21 22 // print bar of asterisks 23 for ( int stars = 0; stars < array[ counter ]; stars++ ) 24 System.out.print( "*" ); 25 26 System.out.println(); // start a new line of output 27 } // end outer for 28 } // end main 29 } // end class BarChart (1 of 2) Line 8 Declare array with initializer list Line 1 9 Use the 0 flag to display one digit grade with a leading 0 Use the 0 flag to display oneLines 232 4 digit grade withor each array F a leading 0 For each array associated number of asterisks element, print associated number of element, print asterisks 2005 Pearson Education, Inc. All rights reserved. Grade distribution: 0009: 1019: 2029: 3039: 4049: 5059: 6069: * 7079: ** 8089: **** 9099: ** 100: * Outline BarChar t.ja va 29 (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved. 30 7.4 Examples Using Arrays (Cont.) Using the elements of an array as counters Use a series of counter variables to summarize data 2005 Pearson Education, 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 // Fig. 7.7: RollDie.java // Roll a sixsided die 6000 times. import java.util.Random; Outline 31 public class RollDie Declare frequency as { array of 7 ints RollDie.java public static void main( String args[] ) { Line 1 0 Random randomNumbers = new Random(); // random number generator Declare int frequency[] = new int[ 7 ]; // array of frequency counters freq uency as array of 7 ints Generate 6000 random // roll die 6000 times; use die value as frequency index integers in range 16 Lines 1 4 31 for ( int roll = 1; roll <= 6000; roll++ ) ++frequency[ 1 + randomNumbers.nextInt( 6 ) ]; System.out.printf( "%s%10s\n", "Face", "Frequency" ); Increment frequency values at index associated with random number // output each array element's value for ( int face = 1; face < frequency.length; face++ ) System.out.printf( "%4d%10d\n", face, frequency[ face ] ); } // end main Generate 6000 random integers in range 16 22 } // end class RollDie Face Frequency 1 988 2 963 3 1018 4 1041 5 978 6 1012 Line 1 4 Increment freq uency values at index associated with random number Program output 2005 Pearson Education, Inc. All rights reserved. 32 7.4 Examples Using Arrays (Cont.) Using arrays to analyze survey results 40 students rate the quality of food 11 Rating scale: 1 mean awful, 1 means excellent 0 0 Place 40 responses in array of integers Summarize results 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 // Fig. 7.8: StudentPoll.java // Poll analysis program. public class StudentPoll { public static void main( String args[] ) { // array of survey responses Outline Declare responses as StudentPoll.ja array to store 40 responses va Declare frequency as (1 of 2) 11 array of int and ignore the first element1 Lines 91 33 int responses[] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 11 4, 8, 6, 8, 10 }; 13 14 // for each answer, select responses element and use that value 15 // as frequency index to determine element to increment 17 ++frequency[ responses[ answer ] ]; 18 20 21 // output each array element's value 22 for ( int rating = 1; rating < frequency.length; rating++ ) 23 System.out.printf( "%d%10d", rating, frequency[ rating ] ); 24 } // end main 25 } // end class StudentPoll 16 for ( int answer = 0; answer < responses.length; answer++ ) 12 int frequency[] = new int[ 11 ]; // array of frequency counters Declare responses as array to store 40 responses 19 System.out.printf( "%s%10s", "Rating", "Frequency" ); Line 12 Declare freq uency as array of 1 1 int For each response, increment and ignore the first element frequency values at index associated with that response Lines 1 7 61 F or each response, increment freq uency values at index associated with that response 2005 Pearson Education, Inc. All rights reserved. Rating Frequency 1 2 2 2 3 2 4 2 5 5 6 11 7 5 8 7 9 1 10 3 Outline 34 StudentPoll.java (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved. 35 Error-Prevention Tip 7.1 An exception indicates that an error has occurred in a program. A programmer often can write code to recover from an exception and continue program execution, rather than abnormally terminating the program. When a program attempts to access an element outside the array bounds, an ArrayIndexOutOfBoundsException occurs. Exception handling is discussed in Chapter 13. 2005 Pearson Education, Inc. All rights reserved. 36 Error-Prevention Tip 7.2 When writing code to loop through an array, ensure that the array index is always greater than or equal to 0 and less than the length of the array. The loop-continuation condition should prevent the accessing of elements outside this range. 2005 Pearson Education, Inc. All rights reserved. 7.5 Case Study: Card Shuffling and Dealing Simulation Program simulates card shuffling and dealing Use random number generation Use an array of reference type elements to represent cards Three classes Card Represent a playing card DeckOfCards Represent a deck of 52 playing cards DeckOfCardsTest Demonstrate card shuffling and dealing 37 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 // Fig. 7.9: Card.java // Card class represents a playing card. public class Card { private String face; // face of card ("Ace", "Deuce", ...) private String suit; // suit of card ("Hearts", "Diamonds", ...) // twoargument constructor initializes card's face and suit Outline Card.java Lines 1 720 38 10 public Card( String cardFace, String cardSuit ) 11 { 12 face = cardFace; // initialize face of card 13 suit = cardSuit; // initialize suit of card 14 } // end twoargument Card constructor 15 16 // return String representation of Card 17 public String toString() 18 { 19 return face + " of " + suit; 20 } // end method toString 21 } // end class Card Return the string representation of a card 2005 Pearson Education, 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 // Fig. 7.10: DeckOfCards.java // DeckOfCards class represents a deck of playing cards. import java.util.Random; Outline 39 Declare deck as array to public class DeckOfCards store Card objects { Constant NUMBER_OF_CARDS indicates DeckOfCards.jav private Card deck[]; // array of Card objects the number of Cards in the deck a private int currentCard; // index of next Card to be dealt private final int NUMBER_OF_CARDS = 52; // constant number of Cards private Random randomNumbers; // random number generator // constructor fills deck of Cards Declare and initialize faces with public DeckOfCards() Strings that represent the face of card { String faces[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", Declare and initialize suits with "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; Strings that represent the suit of String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" }; card deck = new Card[ NUMBER_OF_CARDS ]; // create array of Card objects currentCard = 0; // set currentCard so first Card dealt is deck[ 0 ] randomNumbers = new Random(); // create random number generator array Fill the deck // populate deck with Card objects for ( int count = 0; count < deck.length; count++ ) deck[ count ] = new Card( faces[ count % 13 ], suits[ count / 13 ] ); } // end DeckOfCards constructor (1 of 2) Line 7 Line 9 Lines 15-16 Line 17 Lines 24-26 with Cards 2005 Pearson Education, Inc. All rights reserved. 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 53 54 55 56 57 // shuffle deck of Cards with onepass algorithm public void shuffle() { // after shuffling, dealing should start at deck[ 0 ] again currentCard = 0; // reinitialize currentCard // for each Card, pick another random Card and swap them for ( int first = 0; first < deck.length; first++ ) { // select a random number between 0 and 51 int second = randomNumbers.nextInt( NUMBER_OF_CARDS ); // swap current Card with randomly selected Card Card temp = deck[ first ]; deck[ first ] = deck[ second ]; deck[ second ] = temp; } // end for } // end method shuffle Outline 40 DeckOfCards.jav a (2 of 2) Swap current Card with randomly selected Lines 42-44 Card Line 52 // deal one Card public Card dealCard() Determine whether { deck is empty // determine whether Cards remain to be dealt if ( currentCard < deck.length ) return deck[ currentCard++ ]; // return current Card in array else return null; // return null to indicate that all Cards were dealt } // end method dealCard } // end class DeckOfCards 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 // Fig. 7.11: DeckOfCardsTest.java // Card shuffling and dealing application. public class DeckOfCardsTest { // execute application public static void main( String args[] ) { DeckOfCards myDeckOfCards = new DeckOfCards(); Outline 41 DeckOfCardsT est .java 10 myDeckOfCards.shuffle(); // place Cards in random order 11 12 // print all 52 Cards in the order in which they are dealt 13 for ( int i = 0; i < 13; i++ ) 14 { 15 // deal and print 4 Cards 16 System.out.printf( "%20s%20s%20s%20s\n", 17 myDeckOfCards.dealCard(), myDeckOfCards.dealCard(), 18 myDeckOfCards.dealCard(), myDeckOfCards.dealCard() ); 19 } // end for 20 } // end main 21 } // end class DeckOfCardsTest (1 of 2) 2005 Pearson Education, Inc. All rights reserved. Six of Spades Eight of Spades Six of Clubs Nine of Hearts Queen of Hearts Seven of Clubs Nine of Spades King of Hearts Three of Diamonds Deuce of Clubs Ace of Hearts Ten of Spades Four of Spades Ace of Clubs Seven of Diamonds Four of Hearts Three of Clubs Deuce of Hearts Five of Spades Jack of Diamonds King of Clubs Ten of Hearts Three of Hearts Six of Diamonds Queen of Clubs Eight of Diamonds Deuce of Diamonds Ten of Diamonds Three of Spades King of Diamonds Nine of Clubs Six of Hearts Ace of Spades Four of Diamonds Seven of Hearts Eight of Clubs Deuce of Spades Eight of Hearts Five of Hearts Queen of Spades Jack of Hearts Seven of Spades Four of Clubs Nine of Diamonds Ace of Diamonds Queen of Diamonds Five of Clubs King of Spades Five of Diamonds Ten of Clubs Jack of Spades Jack of Clubs Outline 42 DeckOfCardsT est .java (2 of 2) 2005 Pearson Education, Inc. All rights reserved. 43 7.6 Enhanced for Statement Enhanced for statement New feature of J2SE 5.0 Allows iterates through elements of an array or a collection without using a counter Syntax for ( parameter : arrayName ) statement 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 // Fig. 7.12: EnhancedForTest.java // Using enhanced for statement to total integers in an array. public class EnhancedForTest { public static void main( String args[] ) { int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total for ( int number : array ) total += number; Outline EnhancedForT es t.java 44 For each iteration, assign the next element of array to int variable number, then add it to total 14 15 System.out.printf( "Total of array elements: %d\n", total ); 16 } // end main 17 } // end class EnhancedForTest Total of array elements: 849 2005 Pearson Education, Inc. All rights reserved. 45 7.6 Enhanced for Statement (Cont.) Lines 12-13 are equivalent to for ( int counter = 0; counter < array .length; counter+ + ) total += array[ counter ]; Usage Can access array elements Cannot modify array elements Cannot access the counter indicating the index 2005 Pearson Education, Inc. All rights reserved. 46 7.7 Passing Arrays to Methods To pass array argument to a method Specify array name without brackets Array hourl em peratures is declared as yT int hourl em peratures = yT new int[ 2 4 ]; The method call modifyArray( hourl em peratur yT es ); Passes array hourl em peratures to method yT 2005 Pearson Education, Inc. modifyArray 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 // Fig. 7.13: PassArray.java // Passing arrays and individual array elements to methods. public class PassArray with initializer list { // main creates array and calls modifyArray and modifyElement PassArray.java public static void main( String args[] ) { (1 of 2) int array[] = { 1, 2, 3, 4, 5 }; Pass entire array to methodLine 9 System.out.println( modifyArray "Effects of passing reference to entire array:\n" + Line 19 "The values of the original array are:" ); // output original array elements for ( int value : array ) System.out.printf( " %d", value ); modifyArray( array ); // pass array reference System.out.println( "\n\nThe values of the modified array are:" ); // output modified array elements for ( int value : array ) System.out.printf( " %d", value ); System.out.printf( "\n\nEffects of passing array element value:\n" + "array[3] before modifyElement: %d\n", array[ 3 ] ); Declare 5-int array Outline 47 2005 Pearson Education, Inc. All rights reserved. 29 30 modifyElement( array[ 3 ] ); // attempt to modify array[ 3 ] 31 System.out.printf( Pass array element array[3] to 32 "array[3] after modifyElement: %d\n", array[ 3 ] ); method modifyElement 33 } // end main 34 35 // multiply each element of an array by 2 Method modifyArray PassArray.java 36 public static void modifyArray( int array2[] ) manipulates the array directly 37 { (2 of 2) 38 for ( int counter = 0; counter < array2.length; counter++ ) 39 array2[ counter ] *= 2; Line 30 Method modifyElement 40 } // end method modifyArray 41 manipulates a primitive's copy 42 // multiply argument by 2 Lines 36-40 43 public static void modifyElement( int element ) 44 { Lines 43-48 45 element *= 2; 46 System.out.printf( 47 "Value of element in modifyElement: %d\n", element ); 48 } // end method modifyElement 49 } // end class PassArray Effects of passing reference to entire array: The values of the original array are: Program output 1 2 3 4 5 Outline 48 The values of the modified array are: 2 4 6 8 10 Effects of passing array element value: array[3] before modifyElement: 8 Value of element in modifyElement: 16 array[3] after modifyElement: 8 2005 Pearson Education, Inc. All rights reserved. 49 7.7 Passing Arrays to Methods (Cont.) Notes on passing arguments to methods Two 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 method direct access to caller's data 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 by reference 2005 Pearson Education, Inc. All rights reserved. 50 Performance Tip 7.1 Passing arrays by reference makes sense for performance reasons. If arrays were passed by value, a copy of each element would be passed. For large, frequently passed arrays, this would waste time and consume considerable storage for the copies of the arrays. 2005 Pearson Education, Inc. All rights reserved. 7.8 Case Study: Class GradeBook Using an Array to Store Grades Further evolve class GradeBook Class GradeBook Represent a grade book that stores and analyzes grades Does not maintain individual grade values Repeat calculations require reentering the same grades Can be solved by storing grades in an array 51 2005 Pearson Education, Inc. All rights reserved. // Fig. 7.14: GradeBook.java 1 // Grade book using an array to store test grades. 2 3 public class GradeBook 4 { 5 6 7 8 9 private String courseName; // name of course this GradeBook represents private int grades[]; // array of student grades // twoargument constructor initializes courseName and grades array Outline GradeBook .java 52 (1 of 5) 10 public GradeBook( String name, int gradesArray[] ) 11 { 12 courseName = name; // initialize courseName 13 grades = gradesArray; // store grades 14 } // end twoargument GradeBook constructor 15 16 // method to set the course name 17 public void setCourseName( String name ) 18 { 19 courseName = name; // store the course name 20 } // end method setCourseName 21 22 // method to retrieve the course name 23 public String getCourseName() 24 { 25 return courseName; 26 } // end method getCourseName 27 Declare array grades to store individual grades Line 7 Line 13 Assign the array's reference to instance variable grades 2005 Pearson Education, Inc. All rights reserved. 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 53 54 // display a welcome message to the GradeBook user public void displayMessage() { // getCourseName gets the name of the course System.out.printf( "Welcome to the grade book for\n%s!\n\n", getCourseName() ); } // end method displayMessage // perform various operations on the data public void processGrades() { // output grades array outputGrades(); // call method getAverage to calculate the average grade System.out.printf( "\nClass average is %.2f\n", getAverage() ); // call methods getMinimum and getMaximum System.out.printf( "Lowest grade is %d\nHighest grade is %d\n\n", getMinimum(), getMaximum() ); // call outputBarChart to print grade distribution chart outputBarChart(); } // end method processGrades // find minimum grade public int getMinimum() Outline GradeBook .java 53 (2 of 5) 55 { 56 int lowGrade = grades[ 0 ]; // assume grades[ 0 ] is smallest 57 2005 Pearson Education, Inc. All rights reserved. 58 // loop through grades array 59 for ( int grade : grades ) 60 61 62 63 { // if grade lower than lowGrade, assign it to lowGrade if ( grade < lowGrade ) Loop through = lowGrade grade; // new lowest grade Outline 54 64 } // end for 65 66 return lowGrade; // return lowest grade 67 } // end method getMinimum 68 69 // find maximum grade 70 public int getMaximum() grades to find the lowest grade GradeBook .java (3 of 5) Lines 59-64 Lines 75-80 71 { 72 int highGrade = grades[ 0 ]; // assume grades[ 0 ] is largest 73 74 // loop through grades array 75 76 77 78 for ( int grade : grades ) { // if grade greater than highGrade, assign it to highGrade if ( grade > highGrade ) 79 highGrade = grade; // new highest grade 80 } // end for 81 82 return highGrade; // return highest grade 83 } // end method getMaximum 84 Loop through grades to find the highest grade 2005 Pearson Education, Inc. All rights reserved. 85 // determine average grade for test 86 public double getAverage() 87 { 88 int total = 0; // initialize total 89 90 // sum grades for one student 91 for ( int grade : grades ) 92 total += grade; 93 94 // return average of grades Loop through grades to 95 return (double) total / grades.length; sum grades for one student 96 } // end method getAverage 97 98 // output bar chart displaying grade distribution 99 public void outputBarChart() 100 { 101 System.out.println( "Grade distribution:" ); 102 103 // stores frequency of grades in each range of 10 grades 104 int frequency[] = new int[ 11 ]; 105 106 // for each grade, increment the appropriate frequency 107 for ( int grade : grades ) 108 ++frequency[ grade / 10 ]; 109 Outline GradeBook .java 55 (4 of 5) Lines 91-92 Lines 107-108 Loop through grades to calculate frequency 2005 Pearson Education, Inc. All rights reserved. 110 // for each grade frequency, print bar in chart 111 for ( int count = 0; count < frequency.length; count++ ) 112 { 113 // output bar label ( "0009: ", ..., "9099: ", "100: " ) 114 if ( count == 10 ) 115 System.out.printf( "%5d: ", 100 ); 116 else 117 System.out.printf( "%02d%02d: ", 118 count * 10, count * 10 + 9 ); 119 120 // print bar of asterisks 121 for ( int stars = 0; stars < frequency[ count ]; stars++ ) 122 System.out.print( "*" ); 123 124 System.out.println(); // start a new line of output 125 } // end outer for 126 } // end method outputBarChart 127 Loop through grades 128 // output the contents of the grades array display each grade 129 public void outputGrades() 130 { 131 System.out.println( "The grades are:\n" ); 132 133 // output each student's grade 134 for ( int student = 0; student < grades.length; student++ ) 135 System.out.printf( "Student %2d: %3d\n", 136 student + 1, grades[ student ] ); 137 } // end method outputGrades 138 } // end class GradeBook Outline GradeBook .java 56 (5 of 5) Lines 134-136 to 2005 Pearson Education, Inc. All rights reserved. 57 Software Engineering Observation 7.1 A test harness (or test application) is responsible for creating an object of the class being tested and providing it with data. This data could come from any of several sources. Test data can be placed directly into an array with an array initializer, it can come from the user at the keyboard, it can come from a file (as you will see in Chapter 14), or it can come from a network (as you will see in Chapter 24). After passing this data to the class's constructor to instantiate the object, the test harness should call upon the object to test its methods and manipulate its data. Gathering data in the test harness like this allows the class to manipulate data from several sources. 2005 Pearson Education, Inc. All rights reserved. // Fig. 7.15: GradeBookTest.java 1 // Creates GradeBook object using an array of grades. 2 3 public class GradeBookTest 4 { 5 // main method begins program execution 6 public static void main( String args[] ) 7 { 8 // array of student grades 9 10 int gradesArray[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; 11 12 GradeBook myGradeBook = new GradeBook( 13 "CS101 Introduction to Java Programming", gradesArray ); 14 myGradeBook.displayMessage(); 15 myGradeBook.processGrades(); 16 } // end main 17 } // end class GradeBookTest Outline 58 Declare and initialize gradesArray with 10 elements GradeBookT est .java (1 of 2) Line 10 Line 13 Pass gradesArray to GradeBook constructor 2005 Pearson Education, Inc. All rights reserved. Welcome to the grade book for CS101 Introduction to Java Programming! The grades are: Student 1: 87 Student 2: 68 Student 3: 94 Student 4: 100 Student 5: 83 Student 6: 78 Student 7: 85 Student 8: 91 Student 9: 76 Student 10: 87 Class average is 84.90 Lowest grade is 68 Highest grade is 100 Grade distribution: 0009: 1019: 2029: 3039: 4049: 5059: 6069: * 7079: ** 8089: **** 9099: ** 100: * Outline GradeBookT est .java 59 (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved. 60 7.9 Multidimensional Arrays Multidimensional arrays Tables with rows and columns Two-dimensional array m-by-n array 2005 Pearson Education, Inc. All rights reserved. 61 Fig. 7.16 | Two-dimensional array with three rows and four columns. 2005 Pearson Education, Inc. All rights reserved. 62 7.9 Multidimensional Arrays (Cont.) Arrays of one-dimensional array Declaring two-dimensional array b[2][2] int b[][] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[0][0] and b[0][1] 3 and 4 initialize b[1][0] and b[1][1] int b[][] = { { 1, 2 }, { 3, 4, 5 } }; row 0 contains elements 1 and 2 row 1 contains elements 3, 4 and 5 2005 Pearson Education, Inc. All rights reserved. 63 7.9 Multidimensional Arrays (Cont.) Two-dimensional arrays with rows of different lengths Lengths of rows in array are not required to be the same E.g., int b[][] = { { 1, 2 }, { 3, 4, 5 } }; 2005 Pearson Education, Inc. All rights reserved. 64 7.9 Multidimensional Arrays (Cont.) Creating two-dimensional arrays with arraycreation expressions Can be created dynamically 3-by-4 array int b[][]; b = new int[ 3 ][ 4 ]; Rows can have different number of columns int b[][]; b = new int[ 2 ][ ]; // create 2 rows b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int[ 3 ]; // create 3 columns row 1 for 2005 Pearson Education, Inc. All rights reserved. // Fig. 7.17: InitArray.java 1 // Initializing twodimensional arrays. 2 3 public class InitArray 4 Use nested array initializers { 5 to initialize array1 // create and output twodimensional arrays 6 public static void main( String args[] ) 7 { 8 Use int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; nested array initializers 9 of 10 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; different lengths to 11 initialize array2 12 System.out.println( "Values in array1 by row are" ); 13 outputArray( array1 ); // displays array1 by row 14 15 System.out.println( "\nValues in array2 by row are" ); 16 outputArray( array2 ); // displays array2 by row 17 } // end main 18 Outline InitArray java . 65 (1 of 2) Line 9 Line 10 2005 Pearson Education, Inc. All rights reserved. 19 // output rows and columns of a twodimensional array 20 public static void outputArray( int array[][] ) 21 { array[row].length returns number 22 // loop through array's rows of columns associated with row subscript 23 for ( int row = 0; row < array.length; row++ ) 24 { InitArray java . 25 // loop through columns of current row 26 for ( int column = 0; column < array[ row ].length; column++ ) (2 of 2) 27 System.out.printf( "%d ", array[ row ][ column ] ); 28 Line 26 29 System.out.println(); // start new line of output 30 } // end outer for Line 31 } // end method outputArray Use double-bracket notation to access 27 32 } // end class InitArray two-dimensional array values Values in array1 by row are 1 2 3 4 5 6 Program output Values in array2 by row are 1 2 3 4 5 6 Outline 66 2005 Pearson Education, Inc. All rights reserved. 67 7.9 Multidimensional Arrays (Cont.) Common multidimensional-array manipulations performed with for statements Many common array manipulations use for statements E.g., for ( int column = 0; column < a[ 2 ].length; column++ ) a[ 2 ][ column ] = 0; 2005 Pearson Education, Inc. All rights reserved. 7.10 Case Study: Class GradeBook Using a Two-Dimensional Array Class GradeBook One-dimensional array Store student grades on a single exam 68 Two-dimensional array Store grades for a single student and for the class as a whole 2005 Pearson Education, Inc. All rights reserved. 1 // Fig. 7.18: GradeBook.java 2 // Grade book using a twodimensional array to store grades. 3 4 5 6 Declare two-dimensional array grades public class GradeBook { private String courseName; // name of course this grade book represents private int grades[][]; // twodimensional array of student grades // twoargument constructor initializes courseName and grades array public GradeBook( String name, int gradesArray[][] ) Outline GradeBook .java 69 7 8 9 10 (1 of 7) Line 7 Line 10 11 { 12 courseName = name; // initialize courseName 13 grades = gradesArray; // store grades } // end twoargument GradeBook constructor // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName // method to retrieve the course name public String getCourseName() { return courseName; 14 15 16 17 GradeBook constructor accepts a String and a two-dimensional array 18 19 20 21 22 23 24 25 26 } // end method getCourseName 27 2005 Pearson Education, Inc. All rights reserved. 28 // display a welcome message to the GradeBook user 29 public void displayMessage() 30 { 31 // getCourseName gets the name of the course 32 System.out.printf( "Welcome to the grade book for\n%s!\n\n", 33 getCourseName() ); 34 } // end method displayMessage 35 36 // perform various operations on the data 37 public void processGrades() 38 { 39 // output grades array 40 outputGrades(); 41 42 // call methods getMinimum and getMaximum 43 System.out.printf( "\n%s %d\n%s %d\n\n", 44 "Lowest grade in the grade book is", getMinimum(), 45 "Highest grade in the grade book is", getMaximum() ); 46 47 // output grade distribution chart of all grades on all tests 48 outputBarChart(); 49 } // end method processGrades 50 51 // find minimum grade 52 public int getMinimum() 53 { 54 // assume first element of grades array is smallest 55 int lowGrade = grades[ 0 ][ 0 ]; 56 Outline GradeBook .java 70 (2 of 7) 2005 Pearson Education, Inc. All rights reserved. 57 // loop through rows of grades array 58 for ( int studentGrades[] : grades ) 59 { 60 // loop through columns of current row 61 for ( int grade : studentGrades ) Loop through rows of grades to find 62 { the lowest grade of any 63 // if grade less than lowGrade, assign it to lowGrade student 64 if ( grade < lowGrade ) 65 lowGrade = grade; 66 } // end inner for 67 } // end outer for 68 69 return lowGrade; // return lowest grade 70 } // end method getMinimum 71 72 // find maximum grade 73 public int getMaximum() 74 { 75 // assume first element of grades array is largest 76 int highGrade = grades[ 0 ][ 0 ]; 77 Outline GradeBook .java 71 (3 of 7) Lines 58-67 2005 Pearson Education, Inc. All rights reserved. 78 // loop through rows of grades array 79 for ( int studentGrades[] : grades ) 80 { 81 // loop through columns of current row 82 for ( int grade : studentGrades ) Outline GradeBook .java 72 83 { the highest grade of any student 84 // if grade greater than highGrade, assign it to highGrade 85 if ( grade > highGrade ) 86 highGrade = grade; 87 } // end inner for 88 } // end outer for 89 90 return highGrade; // return highest grade 91 } // end method getMaximum 92 93 // determine average grade for particular set of grades 94 public double getAverage( int setOfGrades[] ) 95 { 96 int total = 0; // initialize total 97 Calculate a particular 98 // sum grades for one student 100 101 102 103 104 105 total += grade; // return average of grades return (double) total / setOfGrades.length; } // end method getAverage Loop through rows of grades to find (4 of 7) Lines 79-88 Lines 94-104 student's semester 99 for ( int grade : setOfGrades ) average 2005 Pearson Education, Inc. All rights reserved. 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 // output bar chart displaying overall grade distribution public void outputBarChart() { System.out.println( "Overall grade distribution:" ); // stores frequency of grades in each range of 10 grades int frequency[] = new int[ 11 ]; // for each grade in GradeBook, increment the appropriate frequency for ( int studentGrades[] : grades ) { for ( int grade : studentGrades ) ++frequency[ grade / 10 ]; Calculate the distribution of } // end outer for all student grades // for each grade frequency, print bar in chart for ( int count = 0; count < frequency.length; count++ ) { // output bar label ( "0009: ", ..., "9099: ", "100: " ) if ( count == 10 ) System.out.printf( "%5d: ", 100 ); else System.out.printf( "%02d%02d: ", count * 10, count * 10 + 9 ); // print bar of asterisks for ( int stars = 0; stars < frequency[ count ]; stars++ ) System.out.print( "*" ); Outline GradeBook .java 73 (5 of 7) Lines 115-119 2005 Pearson Education, Inc. All rights reserved. 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 System.out.println(); // start a new line of output } // end outer for } // end method outputBarChart // output the contents of the grades array public void outputGrades() { System.out.println( "The grades are:\n" ); System.out.print( " " ); // align column heads // create a column heading for each of the tests for ( int test = 0; test < grades[ 0 ].length; test++ ) System.out.printf( "Test %d ", test + 1 ); System.out.println( "Average" ); // student average column heading // create rows/columns of text representing array grades for ( int student = 0; student < grades.length; student++ ) { System.out.printf( "Student %2d", student + 1 ); for ( int test : grades[ student ] ) // output student's grades System.out.printf( "%8d", test ); Outline GradeBook .java 74 (6 of 7) 2005 Pearson Education, Inc. All rights reserved. 159 // call method getAverage to calculate student's average grade; 160 // pass row of grades as the argument to getAverage 161 162 163 164 double average = getAverage( grades[ student ] ); System.out.printf( "%9.2f\n", average ); } // end outer for } // end method outputGrades Outline GradeBook .java 75 165 } // end class GradeBook (7 of 7) 2005 Pearson Education, Inc. All rights reserved. // Fig. 7.19: GradeBookTest.java 1 // Creates GradeBook object using a twodimensional array of grades. 2 3 public class GradeBookTest 4 Declare gradesArray as 3 { 5 // main method begins program execution 6 by-10 array GradeBookT est public static void main( String args[] ) 7 { 8 .java // twodimensional array of student grades 9 10 int gradesArray[][] = { { 87, 96, 70 }, 11 { 68, 87, 90 }, (1 of 2) 12 { 94, 100, 90 }, 13 { 100, 81, 82 }, Lines 10-19 14 { 83, 65, 85 }, 15 { 78, 87, 65 }, 16 { 85, 75, 83 }, 17 { 91, 94, 100 }, 18 { 76, 72, 84 }, 19 { 87, 93, 73 } }; 20 Each row represents a student; each 21 GradeBook myGradeBook = new GradeBook( column represents an exam grade 22 "CS101 Introduction to Java Programming", gradesArray ); 23 myGradeBook.displayMessage(); 24 myGradeBook.processGrades(); 25 } // end main 26 } // end class GradeBookTest Outline 76 2005 Pearson Education, Inc. All rights reserved. Welcome to the grade book for CS101 Introduction to Java Programming! The grades are: Test 1 Test 2 Test 3 Average Student 1 87 96 70 84.33 Student 2 68 87 90 81.67 Student 3 94 100 90 94.67 Student 4 100 81 82 87.67 Student 5 83 65 85 77.67 Student 6 78 87 65 76.67 Student 7 85 75 83 81.00 Student 8 91 94 100 95.00 Student 9 76 72 84 77.33 Student 10 87 93 73 84.33 Lowest grade in the grade book is 65 Highest grade in the grade book is 100 Overall grade distribution: 0009: 1019: 2029: 3039: 4049: 5059: 6069: *** 7079: ****** 8089: *********** 9099: ******* 100: *** Outline GradeBookT est .java 77 (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved. 78 7.11 Variable-Length Argument Lists Variable-length argument lists New feature in J2SE 5.0 Unspecified number of arguments Use ellipsis (...) in method's parameter list Can occur only once in parameter list Must be placed at the end of parameter list Array whose elements are all of the same type 2005 Pearson Education, Inc. All rights reserved. // Fig. 7.20: VarargsTest.java 1 // Using variablelength argument lists. 2 3 public class VarargsTest 4 { 5 // calculate average 6 public static double average( double... numbers ) 7 { 8 double total = 0.0; // initialize total 9 10 Method average 11 // calculate total using the enhanced for statement receives a variable 12 for ( double d : numbers ) length sequence of doubles 13 total += d; 14 15 return total / numbers.length; Calculate the total of the 16 } // end method average doubles in the array 17 18 public static void main( String args[] ) Access numbers.length to obtain 19 { the size of the numbers array 20 double d1 = 10.0; 21 double d2 = 20.0; 22 double d3 = 30.0; 23 double d4 = 40.0; 24 Outline VarargsT est .java 79 (1 of 2) Line 7 Lines 12-13 Line 15 2005 Pearson Education, Inc. All rights reserved. 25 System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n", 26 d1, d2, d3, d4 ); 27 28 System.out.printf( "Average of d1 and d2 is %.1f\n", 29 average( d1, d2 ) ); Invoke method 30 System.out.printf( "Average of d1, d2 and d3 is %.1f\n", Outline VarargsT est .java 80 31 average( d1, d2, d3 ) ); 32 System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n", 33 average( d1, d2, d3, d4 ) ); 34 } // end main Invoke method average 35 } // end class VarargsTest three arguments d1 = 10.0 d2 = 20.0 d3 = 30.0 d4 = 40.0 Average of d1 and d2 is 15.0 Average of d1, d2 and d3 is 20.0 Invoke method average with Average of d1, d2, d3 and d4 is 25.0 average with two arguments with 2) (2 of Line 29 Line 31 Line 33 Program output four arguments 2005 Pearson Education, Inc. All rights reserved. 81 Common Programming Error 7.6 Placing an ellipsis in the middle of a method parameter list is a syntax error. An ellipsis may be placed only at the end of the parameter list. 2005 Pearson Education, Inc. All rights reserved. 82 7.12 Using Command-Line Arguments Command-line arguments Pass arguments from the command line String args[] Appear after the class name in the java command java MyClass a b Number of arguments passed in from command line args.length First command-line argument args[ 0 ] 2005 Pearson Education, Inc. All rights reserved. // Fig. 7.21: InitArray.java 1 // Using commandline arguments to initialize an array. 2 3 public class InitArray 4 { 5 public static void main( String args[] ) 6 InitArray java . { 7 // check number of commandline arguments 8 (1 of 2) if ( args.length != 3 ) 9 Array args stores command10 System.out.println( Line 6 line arguments 11 "Error: Please reenter the entire command, including\n" + Line 9 12 "an array size, initial value and increment." ); Check number of arguments 13 else passed in from the command line Line 16 14 { 15 // get array size from first commandline argument Lines 20-21 16 int arrayLength = Integer.parseInt( args[ 0 ] ); 17 int array[] = new int[ arrayLength ]; // create array Lines 24-25 18 19 // get initial value and increment from commandline argument Obtain first command-line argument 20 int initialValue = Integer.parseInt( args[ 1 ] ); 21 int increment = Integer.parseInt( args[ 2 ] ); 22 23 // calculate value for each array element 24 for ( int counter = 0; counter < array.length; counter++ ) Obtain second and third 25 array[ counter ] = initialValue + increment * counter; command-line arguments 26 27 System.out.printf( "%s%8s\n", "Index", "Value" ); 28 Calculate the value for each array element Outline 83 based on command-line arguments 2005 Pearson Education, Inc. All rights reserved. 29 // display array index and value 30 for ( int counter = 0; counter < array.length; counter++ ) 31 System.out.printf( "%5d%8d\n", counter, array[ counter ] ); 32 } // end else 33 } // end main 34 } // end class InitArray java InitArray Error: Please reenter the entire command, including an array size, initial value and increment. Missing command-line arguments java InitArray 5 0 4 Index Value 0 0 1 4 2 8 3 12 Three command-line arguments are 4 16 5, 0 and 4 java InitArray 10 1 2 Index Value 0 1 1 3 2 5 3 7 Three command-line arguments are 4 9 10, 1 and 2 5 11 6 13 7 15 8 17 9 19 Outline InitArray java . 84 (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved. 7.13 (Optional) GUI and Graphics Case Study: Drawing Arcs Draw rainbow Use arrays Use repetition statement Use Graphics method fillArc 85 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 // Fig. 7.22: DrawRainbow.java // Demonstrates using colors in an array. import java.awt.Color; import java.awt.Graphics; import javax.swing.JPanel; Outline DrawR ainbow .java 86 public class DrawRainbow extends JPanel 7 { 8 // Define indigo and violet 9 10 final Color VIOLET = new Color( 128, 0, 128 ); 11 final Color INDIGO = new Color( 75, 0, 130 ); 12 13 // colors to use in the rainbow, starting from the innermost 14 // The two white entries result in an empty arc in the center 15 private Color colors[] = 16 { Color.WHITE, Color.WHITE, VIOLET, INDIGO, Color.BLUE, 17 Color.GREEN, Color.YELLOW, Color.ORANGE, Color.RED }; 18 19 // constructor 20 public DrawRainbow() 21 { 22 setBackground( Color.WHITE ); // set the background to white 23 } // end DrawRainbow constructor 24 25 // draws a rainbow using concentric circles Set component background 26 public void paintComponent( Graphics g ) 27 { 28 super.paintComponent( g ); 29 30 int radius = 20; // radius of an arch (1 of 2) Line 22 to white 2005 Pearson Education, Inc. All rights reserved. 31 32 // draw the rainbow near the bottomcenter 33 int centerX = getWidth() / 2; 34 int centerY = getHeight() 10; 35 36 // draws filled arcs starting with the outermost 37 for ( int counter = colors.length; counter > 0; counter ) 38 { 39 // set the color for the current arc 40 g.setColor( colors[ counter 1 ] ); 41 42 // fill the arc from 0 to 180 degrees 43 g.fillArc( centerX counter * radius, 44 centerY counter * radius, 45 counter * radius * 2, counter * radius * 2, 0, 180 ); 46 } // end for 47 } // end method paintComponent 48 } // end class DrawRainbow Outline DrawR ainbow .java 87 (2 of 2) Lines 43-45 Draw a filled semicircle 2005 Pearson Education, Inc. All rights reserved. // Fig. 7.23: DrawRainbowTest.java 1 // Test application to display a rainbow. 2 import javax.swing.JFrame; 3 4 public class DrawRainbowTest 5 { 6 public static void main( String args[] ) 7 { 8 DrawRainbow panel = new DrawRainbow(); 9 10 JFrame application = new JFrame(); 11 12 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 13 application.add( panel ); 14 application.setSize( 400, 250 ); 15 application.setVisible( true ); 16 } // end main 17 } // end class DrawRainbowTest Outline DrawR ainbowT es t.java 88 2005 Pearson Education, Inc. All rights reserved. 89 Fig. 7.24 | Drawing a spiral using drawLine (left) and drawArc (right). 2005 Pearson Education, Inc. All rights reserved. 7.14 (Optional) Software Engineering Case Study: Collaboration Among Objects Collaborations When objects communicate to accomplish task Accomplished by invoking operations (methods) 90 One object sends a message to another object 2005 Pearson Education, Inc. All rights reserved. 7.14 (Optional) Software Engineering Case Study (Cont.) Identifying the collaborations in a system Read requirements document to find What ATM should do to authenticate a use What ATM should do to perform transactions 91 For each action, decide Which objects must interact Sending object Receiving object 2005 Pearson Education, Inc. All rights reserved. 92 An object of class... ATM sends the message... displayMessage getInput authenticateUser execute execute Execute to an object of class... Screen Keypad BankDatabase BalanceInquiry Withdrawal Deposit BankDatabase BankDatabase Screen Screen Keypad BankDatabase CashDispenser BankDatabase CashDispenser Screen Keypad DepositSlot BankDatabase Account Account Account Account Account BalanceInquiry getAvailableBalance getTotalBalance displayMessage Withdrawal displayMessage getInput getAvailableBalance isSufficientCashAvailable debit dispenseCash displayMessage getInput isEnvelopeReceived Credit validatePIN getAvailableBalance getTotalBalance debit Credit Deposit BankDatabase Fig. 7.25 | Collaborations in the ATM system. 2005 Pearson Education, Inc. All rights reserved. 7.14 (Optional) Software Engineering Case Study (Cont.) Interaction Diagrams Model interactions use UML Communication diagrams Also called collaboration diagrams Emphasize which objects participate in collaborations 93 Sequence diagrams Emphasize when messages are sent between objects 2005 Pearson Education, Inc. All rights reserved. 7.14 (Optional) Software Engineering Case Study (Cont.) Communication diagrams Objects Modeled as rectangles Contain names in the form objectName : className 94 Objects are connected with solid lines Messages are passed alone these lines in the direction shown by arrows Name of message appears next to the arrow 2005 Pearson Education, Inc. All rights reserved. 95 Fig. 7.26 | Communication diagram of the ATM executing a balance inquiry. 2005 Pearson Education, Inc. All rights reserved. 7.14 (Optional) Software Engineering Case Study (Cont.) Sequence of messages in a communication diagram Appear to the left of a message name Indicate the order in which the message is passed Process in numerical order from least to greatest 96 2005 Pearson Education, Inc. All rights reserved. 97 Fig. 7.27 | Communication diagram for executing a balance inquiry. 2005 Pearson Education, Inc. All rights reserved. 7.14 (Optional) Software Engineering Case Study (Cont.) Sequence diagrams Help model the timing of collaborations Lifeline Dotted line extending down from an object's rectangle Represents the progression of time 98 Activation Thin vertical rectangle Indicates that an object is executing 2005 Pearson Education, Inc. All rights reserved. 99 Fig. 7.28 | Sequence diagram that models a Withdrawal executing. 2005 Pearson Education, Inc. All rights reserved. 100 Fig. 7.29 | Sequence diagram that models a Deposit executing. 2005 Pearson Education, Inc. All rights reserved.

Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

LeTourneau - COSC - 2103
18Classes and Objects: A Deeper Look 2005 Pearson Education, Inc. All rights reserved. 2Instead of this absurd division into sexes, they ought to class people as static and dynamic.- Evelyn WaughIs it a world to hide virtues in?- Wi
LeTourneau - COSC - 2103
19Object-Oriented Programming: Inheritance 2005 Pearson Education, Inc. All rights reserved.2Say not you know another entirely, till you have divided an inheritance with him.- Johann Kasper LavaterThis method is to define as the number of
LeTourneau - COSC - 2103
1 0Object-Oriented Programming: Polymorphism1 2005 Pearson Education, Inc. All rights reserved.2One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them.- John Ronald Reuel TolkienGeneral
LeTourneau - COSC - 2103
1 1GUI Components: Part 11 2005 Pearson Education, Inc. All rights reserved. 2Do you think I can listen all day to such stuff?- Lewis CarrollEven a minor event in the life of a child is an event of that child' s world and thus a wor
LeTourneau - COSC - 2103
1 2Graphics and Java 2DTM1 2005 Pearson Education, Inc. All rights reserved. 2One picture is worth ten thousand words.- Chinese proverbTreat nature in terms of the cylinder, the sphere, the cone, all in perspective.- Paul CzanneC
LeTourneau - COSC - 2103
1 3Exception Handling1 2005 Pearson Education, Inc. All rights reserved. 2It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something.- Franklin Delano RooseveltO! thro
LeTourneau - COSC - 2103
11 4Files and Streams 2005 Pearson Education, Inc. All rights reserved.2I can only assume that a &quot;Do Not File&quot; document is filed in a &quot;Do Not File&quot; file.- Senator Frank Church Senate Intelligence Subcommittee Hearing, 1975Consciousness do
LeTourneau - COSC - 2103
1 5Recursion1 2005 Pearson Education, Inc. All rights reserved.2It's a poor sort of memory that only works backwards. -Lewis Carroll, Alice in Wonderland We must learn to explore all the options and possibilities that confront us in a comple
LeTourneau - COSC - 2103
1 6Searching and Sorting1 2005 Pearson Education, Inc. All rights reserved. 2With sobs and tears he sorted out Those of the largest size .- Lewis CarrollAttempt the end, and never stand to doubt; Nothing's so hard, but search will f
LeTourneau - COSC - 2103
1 7Data Structures1 2005 Pearson Education, Inc. All rights reserved.2Much that I bound, I could not free; Much that I freed returned to me.- Lee Wilson Dodd`Will you walk a little faster?' said a whiting to a snail, `There's a porpoise c
LeTourneau - COSC - 2103
1 9Collections1 2005 Pearson Education, Inc. All rights reserved. 2I think this is the most extraordinary collection of talent, of human knowledge, that has ever been gathered together at the White House-with the possible exception of
LeTourneau - COSC - 2103
2 0Introduction to Java Applets1 2005 Pearson Education, Inc. All rights reserved. 2Observe due measure, for right timing is in all things the most important factor.- Georg Wilhelm Friedrich HegelPainting is only a bridge linking th
LeTourneau - COSC - 2103
2 1Multimedia: Applets and Applications1 2005 Pearson Education, Inc. All rights reserved. 2The wheel that squeaks the loudest . gets the grease.- John Billings (Henry Wheeler Shaw)We'll use a signal I have tried and found farreachi
LeTourneau - COSC - 2103
2 2GUI Components: Part 21 2005 Pearson Education, Inc. All rights reserved. 2An actor entering through the door, you've got nothing. But if he enters through the window, you've got a situation.- Billy Wilder.the force of events wak
LeTourneau - COSC - 2103
2 3Multithreading1 2005 Pearson Education, Inc. All rights reserved. 2Do not block the way of inquiry.- Charles Sanders PeirceA person with one watch knows what time it is; a person with two watches is never sure.- ProverbLearn t
LeTourneau - COSC - 2103
2 4Networking1 2005 Pearson Education, Inc. All rights reserved. 2If the presence of electricity can be made visible in any part of a circuit, I see no reason why intelligence may not be transmitted instantaneously by electricity.- Sa
LeTourneau - COSC - 2103
12 5Accessing Databases with JDBC 2005 Pearson Education, Inc. All rights reserved.2It is a capital mistake to theorize before one has data.- Arthur Conan DoyleNow go, write it before them in a table, and note it in a book, that it may be
LeTourneau - COSC - 2103
12 6Servlets 2005 Pearson Education, Inc. All rights reserved.2A fair request should be followed by the deed in silence.- Dante AlighieriThe longest part of the journey is said to be the passing of the gate.- Marcus Terentius VarroIf no
LeTourneau - COSC - 2103
12 7JavaServer Pages (JSP) 2005 Pearson Education, Inc. All rights reserved.2If it's a good script, I'll do it and if it's a bad script and they pay me enough, I'll do it.- George BurnsA fair request should be followed by the deed in silen
LeTourneau - COSC - 2103
12 8Formatted Output 2005 Pearson Education, Inc. All rights reserved.2All the news that's fit to print.- Adolph S. OchsWhat mad pursuit? What struggle to escape?- John KeatsRemove not the landmark on the boundary of the fields.- Amene
LeTourneau - COSC - 2103
12 9Strings, Characters and Regular Expressions 2005 Pearson Education, Inc. All rights reserved.2The chief defect of Henry King Was chewing little bits of string. -Hilaire Belloc Vigorous writing is concise. A sentence should contain no unne
W. Alabama - CS - 702
Preliminary Information - Subject to ChangeAdvanced Synchronization Facility Proposed Architectural SpecificationPublication # Issue Date:45432 Revision: 2.1 March 2009Advanced Micro Devices 2009 Advanced Micro Devices, Inc. Allrights res
LeTourneau - COSC - 2103
Chapter 10 - Object-Oriented Programming: PolymorphismOutline 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy 10.2.1 Invoking Superclass Methods from Subclass Objects 10.2.2 Using Superclass References with Sub
LeTourneau - COSC - 2103
Outline 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 14.10 14.11 14.12 14.13 Chapter 14 Graphical User Components Part 2Introduction JTextArea Creating a Customized Subclass of JPanel JPanel Subclass that Handles Its Own
LeTourneau - COSC - 2103
Chapter 15 Exception HandlingOutline 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 15.10 15.11 Introduction ExceptionHandling Overview ExceptionHandling Example: Divide by Zero Java Exception Hierarchy Rethrowing an Exception f
LeTourneau - COSC - 2103
Chapter 16 MultithreadingOutline 16.1 Introduction 16.2 Thread States: Life Cycle of a Thread 16.3 Thread Priorities and Thread Scheduling 16.4 Creating and Executing Threads 16.5 Thread Synchronization 16.6 Producer/Consumer Relationsh
LeTourneau - COSC - 2103
Chapter 17 Files and StreamsOutline 17.1 17.2 17.3 17.4 17.5 17.6 17.7 17.8 17.9 17.10 17.11 17.12 17.13 Introduction Data Hierarchy Files and Streams Class File Creating a SequentialAccess File Reading Data from a Sequent
Mich Tech - CM - 4310
CM 4310, Chemical Process Safety/Environment Homework #1Fall `08 Mon. 01 Dec., '081. Global Energy Balance. Problems 2 and 3 Chapter 1, page 32 and 33.2. Partitioning of Pentachlorophenol in a Pond Problem 5 of Chapter 5. This is the same probl
Mich Tech - CM - 4310
Level I, II and III Fugacity Calculations INPUT PARAMETERS Chemical name =&gt; System temperature, deg C =&gt; Molecular weight, g/mol =&gt; Melting point, deg C =&gt; Dissociation const., log pKa=&gt; pH of data determination =&gt; pH of environment =&gt;
Mich Tech - CM - 4310
CM 4310, Chemical Process Safety/Environment Homework #1Fall `08 Mon. 01 Dec., '081. Global Energy Balance. Problems 2 and 3 Chapter 1, page 32 and 33. 2. Global Energy Balance: No Atmosphere a) Energy Balance: &quot;Rate of Solar Energy Absorbed&quot; = &quot;
Mich Tech - CM - 4310
CM 4310, Green Engineering Homework #2Fall `08 Fri. Dec. 05, '081. Environmental Risk Index Calculations for Solvent Recovery and Recycle Problem 5 of Chapter 11, page 396. Assume that the maximum incremental reactivity, MIR, for ethyl acetate is