Presentation is loading. Please wait.

Presentation is loading. Please wait.

 1992-2007 Pearson Education, Inc. All rights reserved. 1 7 7 Arrays.

Similar presentations


Presentation on theme: " 1992-2007 Pearson Education, Inc. All rights reserved. 1 7 7 Arrays."— Presentation transcript:

1  1992-2007 Pearson Education, Inc. All rights reserved. 1 7 7 Arrays

2  1992-2007 Pearson Education, Inc. All rights reserved. 2 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.

3  1992-2007 Pearson Education, Inc. All rights reserved. 3 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 Case Study: Card Shuffling and Dealing Simulation 7.6 Enhanced for Statement 7.7 Passing Arrays to Methods 7.8 Case Study: Class GradeBook Using an Array to Store Grades 7.9 Multidimensional Arrays 7.10 Case Study: Class GradeBook Using a Two-Dimensional Array 7.11 Variable-Length Argument Lists 7.12 Using Command-Line Arguments 7.13 (Optional) GUI and Graphics Case Study: Drawing Arcs 7.14 (Optional) Software Engineering Case Study: Collaboration Among Objects 7.15 Wrap-Up

4  1992-2007 Pearson Education, Inc. All rights reserved. 4 7.1 Introduction Arrays – Data structures – Related data items of same type – Remain same size once created Fixed-length entries

5  1992-2007 Pearson Education, Inc. All rights reserved. 5 7.2 Arrays Array – Group of variables Have same type – Reference type

6  1992-2007 Pearson Education, Inc. All rights reserved. 6 Fig. 7.1 | A 12-element array.

7  1992-2007 Pearson Education, Inc. All rights reserved. 7 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 ]

8  1992-2007 Pearson Education, Inc. All rights reserved. 8 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, short or char, but not long.

9  1992-2007 Pearson Education, Inc. All rights reserved. 9 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

10  1992-2007 Pearson Education, Inc. All rights reserved. 10 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 the [] following c indicate that – c is a variable refering to an array – or a reference variabe in the assignment statement c refers to a 12 integer element array – default initial values 0 for numerial variables: false for boolean null for reference types

11  1992-2007 Pearson Education, Inc. All rights reserved. 11 7.3 Declaring and Creating Arrays We can create arrays of objects too String b[] = new String[ 100 ]; this is possible double [] array1, array2; equivalent to double array1{]; double array2[]; or double[] array1; double[] array2;

12  1992-2007 Pearson Education, Inc. All rights reserved. 12 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.

13  1992-2007 Pearson Education, Inc. All rights reserved. 13 7.4 Examples Using Arrays Declaring arrays Creating arrays Initializing arrays Manipulating array elements

14  1992-2007 Pearson Education, Inc. All rights reserved. 14 7.4 Examples Using Arrays Creating and initializing an array – Declare array – Create array – Initialize array elements

15  1992-2007 Pearson Education, Inc. All rights reserved. 15 Outline InitArray.java Line 8 Declare array as an array of ints Line 10 Create 10 ints for array; each int is initialized to 0 by default Line 15 array.length returns length of array Line 16 array[counter] returns int associated with index in array Program output Declare array as an array of int s Create 10 int s for array ; each int is initialized to 0 by default array.length returns length of array array[counter] returns int associated with index in array Each int is initialized to 0 by default

16  1992-2007 Pearson Education, Inc. All rights reserved. 16 1 // Fig. 7.2: InitArray.java 2 // Creating an array. 3 4 public class InitArray 5 { 6 public static void main( String args[] ) 7 { 8 int array[]; // declare array named array 9 10 array = new int[ 10 ]; // create the space for array 11 12 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings 13 14 // output each array element's value 15 for ( int counter = 0; counter < array.length; counter++ ) 16 System.out.printf( "%5d%8d\n", counter, array[ counter ] ); 17 } // end main 18 } // end class InitArray

17  1992-2007 Pearson Education, Inc. All rights reserved. 17 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[] = { 10, 20, 30, 40, 50 }; – Creates a five-element array – Index values of 0, 1, 2, 3, 4 – Do not need keyword new

18  1992-2007 Pearson Education, Inc. All rights reserved. 18 Outline InitArray.java Line 9 Declare array as an array of ints Line 9 Compiler uses initializer list to allocate array Program output Declare array as an array of int s Compiler uses initializer list to allocate array

19  1992-2007 Pearson Education, Inc. All rights reserved. 19 1 // Fig. 7.3: InitArray.java 2 // Initializing the elements of an array with an array initializer. 3 4 public class InitArray { 6 public static void main( String args[] ) 7 { 8 // initializer list specifies the value for eachelement 9 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 10 11System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings 12 13 // output each array element's value 14 for ( int counter = 0; counter < array.length; counter++ ) 15 System.out.printf( "%5d%8d\n", counter, array[ counter ] ); 16 } // end main 17 } // end class InitArray

20  1992-2007 Pearson Education, Inc. All rights reserved. 20 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; System.out.printf( "%s%8s\n", "Index", "Value" ); // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] );

21  1992-2007 Pearson Education, Inc. All rights reserved. 21 7.4 Examples Using Arrays (Cont.) Calculating a value to store in each array element – Initialize elements of 10-element array to even integers

22  1992-2007 Pearson Education, Inc. All rights reserved. 22 Outline InitArray.java Line 8 Declare constant variable Line 9 Declare and create array that contains 10 ints Line 13 Use array index to assign array Program output

23  1992-2007 Pearson Education, Inc. All rights reserved. 23 final int ARRAY_LENGTH = 10; // declare constant 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" ); // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] );

24  1992-2007 Pearson Education, Inc. All rights reserved. 24 Good Programming Practice 7.2Good 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.

25  1992-2007 Pearson Education, Inc. All rights reserved. 25 Getting the elements of an array from The user

26  1992-2007 Pearson Education, Inc. All rights reserved. 26 Scanner input = new Scanner(System.in); final int ARRAY_LENGTH = 10; // declare constant int array[] = new int[ ARRAY_LENGTH ]; // create array // get th value for each array element from user for ( int counter = 0; counter < array.length; counter++ ) { System.out.print(“Enter ” + counter + “th element:”); array[ counter ] =input.nextInt(); } // rest of the program is th same

27  1992-2007 Pearson Education, Inc. All rights reserved. 27 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

28  1992-2007 Pearson Education, Inc. All rights reserved. 28 Common Programming Error 7.4 Assigning a value to a constant after the variable has been initialized is a compilation error.

29  1992-2007 Pearson Education, Inc. All rights reserved. 29 Common Programming Error 7.5 Attempting to use a constant before it is initialized is a compilation error.

30  1992-2007 Pearson Education, Inc. All rights reserved. 30 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

31  1992-2007 Pearson Education, Inc. All rights reserved. 31 Outline SumArray.java Line 8 Declare array with initializer list Lines 12-13 Sum all array values Program output

32  1992-2007 Pearson Education, Inc. All rights reserved. 32 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total for ( int counter = 0; counter < array.length; counter++ ) total += array[ counter ]; System.out.printf( "Total of array elements: %d\n", total );

33  1992-2007 Pearson Education, Inc. All rights reserved. 33 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

34  1992-2007 Pearson Education, Inc. All rights reserved. 34 Outline BarChart.java (1 of 2) Line 8 Declare array with initializer list Line 19 Use the 0 flag to display one- digit grade with a leading 0 Lines 23-24 For each array element, print associated number of asterisks Declare array with initializer list For each array element, print associated number of asterisks Use the 0 flag to display one- digit grade with a leading 0

35  1992-2007 Pearson Education, Inc. All rights reserved. 35 Outline BarChart.java (2 of 2) Program output

36  1992-2007 Pearson Education, Inc. All rights reserved. 36 7.4 Examples Using Arrays (Cont.) Using the elements of an array as counters – Use a series of counter variables to summarize data

37  1992-2007 Pearson Education, Inc. All rights reserved. 37 Outline RollDie.java Line 10 Declare frequency as array of 7 ints Lines 13-14 Generate 6000 random integers in range 1-6 Line 14 Increment frequency values at index associated with random number Program output

38  1992-2007 Pearson Education, Inc. All rights reserved. 38 import java.util.Random; Random randomNumbers = new Random(); // random number generator int frequency[] = new int[ 7 ]; // array of frequency counters // roll die 6000 times; use die value as frequency index for ( int roll = 1; roll <= 6000; roll++ ) ++frequency[ 1 + randomNumbers.nextInt( 6 ) ]; System.out.printf( "%s%10s\n", "Face", "Frequency" ); // output each array element's value for ( int face = 1; face < frequency.length; face++ ) System.out.printf( "%4d%10d\n", face, frequency[ face ] );

39  1992-2007 Pearson Education, Inc. All rights reserved. 39 7.4 Examples Using Arrays (Cont.) Using arrays to analyze survey results – 40 students rate the quality of food 1-10 Rating scale: 1 means awful, 10 means excellent – Place 40 responses in array of integers – Summarize results

40  1992-2007 Pearson Education, Inc. All rights reserved. 40 Outline StudentPoll.java (1 of 2) 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 Declare responses as array to store 40 responses Declare frequency as array of 11 int and ignore the first element For each response, increment frequency values at index associated with that response

41  1992-2007 Pearson Education, Inc. All rights reserved. 41 Outline StudentPoll.java (2 of 2) Program output

42  1992-2007 Pearson Education, Inc. All rights reserved. 42 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.

43  1992-2007 Pearson Education, Inc. All rights reserved. 43 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.

44  1992-2007 Pearson Education, Inc. All rights reserved. 44 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 – Represents a playing card DeckOfCards – Represents a deck of 52 playing cards DeckOfCardsTest – Demonstrates card shuffling and dealing

45  1992-2007 Pearson Education, Inc. All rights reserved. 45 Outline Card.java Lines 17-20 Return the string representation of a card

46  1992-2007 Pearson Education, Inc. All rights reserved. 46 Outline Card.java Lines 17-20

47  1992-2007 Pearson Education, Inc. All rights reserved. 47 Outline DeckOfCards.java (1 of 2) Line 7 Line 9 Lines 15-16 Line 17 Lines 24-26 Declare deck as array to store Card objects Constant NUMBER_OF_CARDS indicates the number of Cards in the deck Declare and initialize faces with String s that represent the face of card Declare and initialize suits with String s that represent the suit of card Fill the deck array with Card s

48  1992-2007 Pearson Education, Inc. All rights reserved. 48 Outline DeckOfCards.java (2 of 2) Lines 42-44 Line 52 Swap current Card with randomly selected Card Determine whether deck is empty

49  1992-2007 Pearson Education, Inc. All rights reserved. 49 Outline DeckOfCardsTest.java (1 of 2)

50  1992-2007 Pearson Education, Inc. All rights reserved. 50 Outline DeckOfCardsTest.java (2 of 2)

51  1992-2007 Pearson Education, Inc. All rights reserved. 51 7.6 Enhanced for Statement Enhanced for statement – Iterates through elements of an array or a collection without using a counter – Syntax for ( parameter : arrayName ) statement

52  1992-2007 Pearson Education, Inc. All rights reserved. 52 Outline EnhancedForTest.java

53  1992-2007 Pearson Education, Inc. All rights reserved. 53 7.6 Enhanced for Statement (Cont.) 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; System.out.printf( "Total of array elements: %d\n", total );

54  1992-2007 Pearson Education, Inc. All rights reserved. 54 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

55  1992-2007 Pearson Education, Inc. All rights reserved. 55 7.7 Passing Arrays to Methods To pass array argument to a method – Specify array name without brackets Array hourlyTemperatures is declared as int hourlyTemperatures = new int[ 24 ]; The method call modifyArray( hourlyTemperatures ); Passes array hourlyTemperatures to method modifyArray

56  1992-2007 Pearson Education, Inc. All rights reserved. 56 Outline PassArray.java (1 of 2) Line 9 Line 19 Declare 5 - int array with initializer list Pass entire array to method modifyArray

57  1992-2007 Pearson Education, Inc. All rights reserved. 57 Outline PassArray.java (2 of 2) Line 30 Lines 36-40 Lines 43-48 Program output Pass array element array[3] to method modifyElement Method modifyArray manipulates the array directly Method modifyElement manipulates a primitive’s copy

58  1992-2007 Pearson Education, Inc. All rights reserved. 58 7.7 Passing Arrays to Methods (Cont.) // Fig. 7.13: PassArray.java // Passing arrays and individual array elements to methods. public class PassArray { // main creates array and calls modifyArray and modifyElement public static void main( String args[] ) { int array[] = { 1, 2, 3, 4, 5 }; System.out.println( "Effects of passing reference to entire array:\n" + "The values of the original array are:" ); // output original array elements for ( int value : array ) System.out.printf( " %d", value );

59  1992-2007 Pearson Education, Inc. All rights reserved. 59 7.7 Passing Arrays to Methods (Cont.) 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 ] ); modifyElement( array[ 3 ] ); // attempt to modify array[ 3 ] System.out.printf( "array[3] after modifyElement: %d\n", array[ 3 ] ); } // end main

60  1992-2007 Pearson Education, Inc. All rights reserved. 60 // multiply each element of an array by 2 public static void modifyArray( int array2[] ) { for ( int counter = 0; counter < array2.length; counter++ ) array2[ counter ] *= 2; } // end method modifyArray // multiply argument by 2 public static void modifyElement( int element ) { element *= 2; System.out.printf( "Value of element in modifyElement: %d\n", element ); } // end method modifyElement } // end class PassArray

61  1992-2007 Pearson Education, Inc. All rights reserved. 61 Effects of passing reference to entire array: The values of the original array are: 1 2 3 4 5 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 output

62  1992-2007 Pearson Education, Inc. All rights reserved. 62 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 – Every primitive type is passed-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 – Every object is passed-by-reference Arrays are objects Therefore, arrays are passed by reference

63  1992-2007 Pearson Education, Inc. All rights reserved. 63 7.7 Passing Arrays to Methods (Cont.) public class PassValues { public static void main(String args[]) { int a = 5, b = 10; // printing before change System.out.printf(“a: %d b:%d\n”,a,b); change(a,b); // printing after change System.out.printf(“a: %d b:%d\n”,a,b); } // end of main

64  1992-2007 Pearson Education, Inc. All rights reserved. 64 7.7 Passing Arrays to Methods (Cont.) public static void change(int x, int y) { int temp = x; x = y; y = temp; System.out.printf(“x: %d y:%d\n”,x,y); } // end of change method } // end of class PassValue

65  1992-2007 Pearson Education, Inc. All rights reserved. 65 7.7 Passing Arrays to Methods (Cont.) public class PassReference { public static void main(String args[]) { MyInt a = new MyInt(5); MyInt b = new MyInt(10); // printing before change System.out.printf(“a: %d b:%d\n”,a.value,b.value); change(a,b); // printing after change System.out.printf(“a: %d b:%d\n”,a.value,b.value); } // end of main

66  1992-2007 Pearson Education, Inc. All rights reserved. 66 7.7 Passing Arrays to Methods (Cont.) public static void change(MyInt x, MyInt y) { int temp = x.value; x.value = y.value; y.value = temp; System.out.printf(“x: %d y:%d\n”,x.value,y.value); } // end of change method } // end of class PassValue

67  1992-2007 Pearson Education, Inc. All rights reserved. 67 7.7 Passing Arrays to Methods (Cont.) public class MyInt { public int value; public MyInt(int x) { value = x; } // end constructor } // end class MyInt /* in general avoid this do not declare value as a public get its value with getValue() method Here for illustration and simplicity declare value as public */

68  1992-2007 Pearson Education, Inc. All rights reserved. 68 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.

69  1992-2007 Pearson Education, Inc. All rights reserved. 69 A generic array class Develop a gneric array class called MyArray including many methods for – geting arrays – pringting the array – calculating sum, average,standard deviation, minimum, maximum,.. – modifying arrays: multiply by two store in another array – finding distinct values of arrays – sorting, searching in arrays – fining union, intersetion of two arrays

70  1992-2007 Pearson Education, Inc. All rights reserved. 70 A generic array class public class MyArray { private int[] myArray; // constructor public MyArray(int[] theArray) { myArray = theArray; // initialized elsewhere in another class // just pass the reference }

71  1992-2007 Pearson Education, Inc. All rights reserved. 71 A generic array class public int maximum() { int max = myArray[0]; for(int e : myArray) // loop over elements if(e > max) // here e represent the element max = e; return max; }

72  1992-2007 Pearson Education, Inc. All rights reserved. 72 A generic array class public int maxPosition() { int max = myArray[0]; int position = 0; for(int i=0;i < myArray.length;i++) // loop over index if(myArray[i] > max) // i is the index of the array { max = myArray[i]; position = i; } return position; }

73  1992-2007 Pearson Education, Inc. All rights reserved. 73 A generic array class this methods take an array and return its maximum or position of the maximum value as an intger primitive variable How to call such methods in another class int[] a = {1,2,3,4,5}; // create a myA type object sening array a to its constructor MyArray myA = new MyArray(a); // initilize myA // call the maximum method of over myA int maxOfa = myA.maximum(); int posMax = myA.maxPosition();

74  1992-2007 Pearson Education, Inc. All rights reserved. 74 A generic array class A procedural approach for such mehods is declaring each method in the same class as arrays are defined

75  1992-2007 Pearson Education, Inc. All rights reserved. 75 public class ArrayMetodsProcedural { public static void main(String args[]) { int[] a = {1.2.3.4.5}; int maxOfA = maximum(a); int posOfA = maxPosition(a); // print these } // end of main method

76  1992-2007 Pearson Education, Inc. All rights reserved. 76 public static int maximum( int[] myArray) { int max = myArray[0]; for(int i : myArray) // loop over elements if(i > max) // here i represent the element max = i; return max; } // end of maximum // write the maxPosition method as an exercise } end of class arrayMethodsProcedural

77  1992-2007 Pearson Education, Inc. All rights reserved. 77 A generic array class Methods may also return arrays as rferences – what if thee are more then one maximum value in an array how can the possition of each can be returned – e.g. a = {1,2,5,1,5} – maximum value is 5 its positions are 2 and 4 – so an array returning positions should be {2,4} Other examples – copying an array – finding unions, intersection of arrays – inverting an array – reversing its elements – Searching arrays

78  1992-2007 Pearson Education, Inc. All rights reserved. 78 A generic array class Example inverting an array elements a = {2.4.6.2.5} ainv = {5.2.6.4.2} a method that takes as the original array and modifys the original array a method that takes the original array and returns a new invered array a method that takes the original array and another array as parameters and modify the second array a method that creates a MyArray objcet and initialize it with the inverted array returning the reference of the MyArray objcet

79  1992-2007 Pearson Education, Inc. All rights reserved. 79 A generic array class public static void invert1(int[] array) { int temp, n = array.length; for( int i = 0 ; i <= n/2-1 ; i++ ) { temp = array[i]; array[i] = array[n-i-1] = ; array[n-i-1] = temp; } // end of for loop } // end of method

80  1992-2007 Pearson Education, Inc. All rights reserved. 80 A generic array class public static int[] invert2(int[] array ) { int n = array.length; int[] invArray = new int[n]; for( int i = 0 ; i < n ; i++ ) invArray[i] = array[n-i-1]; return invArray; } // end of method

81  1992-2007 Pearson Education, Inc. All rights reserved. 81 A generic array class public static void invert3(int[] array,int[] invArray ) { int n = array.length; invArray = new int[n]; for( int i = 0 ; i < n ; i++ ) invArray[i] = array[n-i-1]; } // end of method

82  1992-2007 Pearson Education, Inc. All rights reserved. 82 A generic array class public class InvertStatic { public static void main(String args[]) [ int[] a = {1.4.3.7.6}; invert1(a); // display array a it is inverted int b[] = new int[a.length]; // same lenght as array a invert3(a,b); // display a and b // b is the original array int[] c = invert2(a); // print c } // end of main method

83  1992-2007 Pearson Education, Inc. All rights reserved. 83 non static versions the non static versions of the invert1, invert2 and invert3 methods are called over objcets say lets create MyArray type objects and call these methods on these objcets

84  1992-2007 Pearson Education, Inc. All rights reserved. 84 public class MyArray { int[] myArray; public MyArray(int[] myArray) { this.myArray = myArray; }

85  1992-2007 Pearson Education, Inc. All rights reserved. 85 // invert1 has no parameter and retrurn no parameter // takes the instance variable myArray and inverts it public void invert1() { int temp, n = myArray.length; for( int i = 0 ; i <= n/2-1 ; i++ ) { temp = myArray[i]; myArray[i] = myArray[n-i-1]; myArray[n-i-1] = temp; } // end of for loop } // end of method

86  1992-2007 Pearson Education, Inc. All rights reserved. 86 calling invert1 from another class public class InvertTest {ddyt public static void main(String args[]) { int[] a = {1,4,2,5,9}; MyArray myA = new MyArray(a); myA.invert1(); // display array a it is inverted }

87  1992-2007 Pearson Education, Inc. All rights reserved. 87 other methods of the MyArray class public class MyArray { int[] myArray; public MyArray(int[] myArray) { this.myArray = myArray; } public void invert1() {..... }

88  1992-2007 Pearson Education, Inc. All rights reserved. 88 public int[] invert2() { int n = myArray.length; int[] invArray = new int[n]; for( int i = 0 ; i < n ; i++ ) invArray[i] = myArray[n-i-1]; return invArray; } // end of method

89  1992-2007 Pearson Education, Inc. All rights reserved. 89 how to call invert2 from main public class InvertTest { public static void main(String args[]) { int[] a = {1,4,2,5,9}; MyArray myA = new MyArray(a); int[] b = myA.invert2(); // display array b it is inverted version of array a } // end of main } // end of calss InvertTest

90  1992-2007 Pearson Education, Inc. All rights reserved. 90 finding the position of maximum add another method to the MyArray class so that it will return the indesis of the maximum element in an array there may be more then one index so the return type should be an array whose length is equal or shorther then the original array

91  1992-2007 Pearson Education, Inc. All rights reserved. 91 public class MyArray { int[] myArray; // constructor and other methods

92  1992-2007 Pearson Education, Inc. All rights reserved. 92 public int[] maxPosition(); { int[] postemp = new int[myArray.length] int max=myArray[0],nPos = -1; for(int i=0;i<myArray.length;i++) { if(myArray[i] > max) { max = myArray[i]; nPos = 0; postemp[nPos] = i; } else if (myArray[i] == max) { nPos++; postemp[nPos] = i; }

93  1992-2007 Pearson Education, Inc. All rights reserved. 93 int[] positions = new int[nPos+1]; // copy the temorary array to the position array for(int i = 0;i < positions.lentgth;i++) positions[i] = postemp[i]; return positions; } // end of method

94  1992-2007 Pearson Education, Inc. All rights reserved. 94 Searching in an array Linear search Add as a method to MyArray class Take the input a key an integer to be searched in the instance variable of MyArray class if found return the possition of the key if not fournd return -1

95  1992-2007 Pearson Education, Inc. All rights reserved. 95 public int linearSearch(int key) { // loop through array sequentially for (int i = 0 ; i < myArray.length ; i++ ) if ( myArray[i] == key ) return i; // return index of integer return -1; // integer not found in array } // end of method

96  1992-2007 Pearson Education, Inc. All rights reserved. 96 Test class for linear search import java.util.Scanner public class LinearSearchTest { public static void main(String args[]) { int[] a = {1,4,2,5,9}; MyArray myA = new MyArray(a); // get a key from the user; Scanner input = new Scanner(System.in); System.out.print(“Enter the key:”); int searchKey = input.nextInt(); // search the key in the array int searchRes = myA.linearSearch(searchKey); // display search results } // end of main } // end class

97  1992-2007 Pearson Education, Inc. All rights reserved. 97 Exercise This version of the linear search method is restricted If the search key occors more then one possition in the array all of these should be returned – As an array of possitions – a = {2,4,2,5,2} – key =2 then – Return {0,2,4} possition array – key =7 – Return {-1} key not fournd

98  1992-2007 Pearson Education, Inc. All rights reserved. 98 7.8 Case Study: Class GradeBook Using an Array to Store Grades Further evolve class GradeBook Class GradeBook – Represents 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

99  1992-2007 Pearson Education, Inc. All rights reserved. 99 Outline GradeBook.java (1 of 5) Line 7 Line 13 Declare array grades to store individual grades Assign the array’s reference to instance variable grades

100  1992-2007 Pearson Education, Inc. All rights reserved. 100 Outline GradeBook.java (2 of 5)

101  1992-2007 Pearson Education, Inc. All rights reserved. 101 Outline GradeBook.java (3 of 5) Lines 59-64 Lines 75-80 Loop through grades to find the lowest grade Loop through grades to find the highest grade

102  1992-2007 Pearson Education, Inc. All rights reserved. 102 Outline GradeBook.java (4 of 5) Lines 91-92 Lines 107-108 Loop through grades to sum grades for one student Loop through grades to calculate frequency

103  1992-2007 Pearson Education, Inc. All rights reserved. 103 Outline GradeBook.java (5 of 5) Lines 134-136 Loop through grades to display each grade

104  1992-2007 Pearson Education, Inc. All rights reserved. 104 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.

105  1992-2007 Pearson Education, Inc. All rights reserved. 105 Outline GradeBookTest.java (1 of 2) Line 10 Line 13 Declare and initialize gradesArray with 10 elements Pass gradesArray to GradeBook constructor

106  1992-2007 Pearson Education, Inc. All rights reserved. 106 Outline GradeBookTest.java (2 of 2) Program output

107  1992-2007 Pearson Education, Inc. All rights reserved. 107 7.9 Multidimensional Arrays public class copyArrayTest { public static void main(....) { int[] a = {1,2,3}; int [] b = copyArray(a); // print... } // end of main public static int[] copyArray(int a[]) { int[] b = new int[a.length]; for(int i = 0 ; i < a.length ; i++) b[i] = a[i]; return b; } // end of method } // end of class

108  1992-2007 Pearson Education, Inc. All rights reserved. 108 7.9 Multidimensional Arrays Multidimensional arrays – Tables with rows and columns Two-dimensional array m-by-n array

109  1992-2007 Pearson Education, Inc. All rights reserved. 109 Fig. 7.16 | Two-dimensional array with three rows and four columns.

110  1992-2007 Pearson Education, Inc. All rights reserved. 110 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

111  1992-2007 Pearson Education, Inc. All rights reserved. 111 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 } };

112  1992-2007 Pearson Education, Inc. All rights reserved. 112 7.9 Multidimensional Arrays (Cont.) Creating two-dimensional arrays with array- creation expressions – 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 for row 1

113  1992-2007 Pearson Education, Inc. All rights reserved. 113 Outline InitArray.java (1 of 2) Line 9 Line 10

114  1992-2007 Pearson Education, Inc. All rights reserved. 114 Outline InitArray.java (2 of 2) Line 26 Line 27 Program output

115  1992-2007 Pearson Education, Inc. All rights reserved. 115 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;

116  1992-2007 Pearson Education, Inc. All rights reserved. 116 public class My2DimArray { int[][] twoDimArray; // constructor public My2DimArray(int[][] newArray) { twoDimArray = newArray; }

117  1992-2007 Pearson Education, Inc. All rights reserved. 117 public int[] rowSum() { int sum; int n = twoDimArray.length; int[] sumOfRaws = new int [n]; for ( int i = 0 ; i < n ; i++ ) { sum = 0; for(int j = 0 ; j < twoDimArray[i].length ; j++ ) sum += twoDimArray[i][j]; sumOfRaws[i] = sum; } // end of outer loop return sumOfRaws; } // end of method

118  1992-2007 Pearson Education, Inc. All rights reserved. 118 Sum of columns if array is regtangular public int[] columnSum() { int sum; int n = twoDimArray[0].length; int m = twoDimArray.length; int[] sumOfColumns = new int [n]; for ( int i = 0 ; i < n ; i++ ) { sum = 0; for(int j = 0 ; j < m ; j++ ) sum += twoDimArray[j][i]; sumOfColumns[i] = sum; } // end of outer loop return sumOfRaws; } // end of method

119  1992-2007 Pearson Education, Inc. All rights reserved. 119 Exercise Write a version of the column sum method for arrays whose number of elements in each row is not equal – They are not regtangular arrays E.g.: array = {{1,3}, {2,6,4}, {2} } sumOfRaws = {5,9,4}

120  1992-2007 Pearson Education, Inc. All rights reserved. 120 public double[] rawAverages() { double[] ave = new double[twoDimArray.length]; for ( int i = 0 ; i < twoDimArray.length ; i++ ) ave[i] = getAverage(twoDimArray[i]); return ave; } public double getAverage(int a[]) { int sum = 0; for(int element : a ) sum += element; return (double) sum / a.length; }

121  1992-2007 Pearson Education, Inc. All rights reserved. 121 public int[] columnMax() {... } public int[] rawMax() {... } Write their columnMin and rawMin versions as well

122  1992-2007 Pearson Education, Inc. All rights reserved. 122 public int[][] transpose() { int n = twoDimArray.length; int m = twoDimArray[0].length; int[][] transpose = new int[m][n]; for(int i = 0;i < n;i++) for(int j = 0; j < m; j++ ) transpose[j][i] = twoDimArray[i][j]; return transpose; }

123  1992-2007 Pearson Education, Inc. All rights reserved. 123 İsRectenge method is rectengle is a boolean method returns true or false Check whether the instance variable of the twoDimArray class is a regtengular array or not A two dimensional array to be a rectenge: length of each raw should be the same length of raw 0 = length of raw 1 length of raw 0 = length of raw 2 length of raw 0 = length of raw 3...

124  1992-2007 Pearson Education, Inc. All rights reserved. 124 public boolean isRectenge() { boolean isRect = true; int n = twoDimArray.length; int m = twoDimArray[0].length; int i = 1; while(isRect && i < n) { isRect = (twoDimArray[i].length == m) && isRect; i++; } ret1urn isRect; }

125  1992-2007 Pearson Education, Inc. All rights reserved. 125 Another version of the isRectange method public boolean isRectenge() { boolean isRect = true; int n = twoDimArray.length; int m = twoDimArray[0].length; int i = 0; while(isRect && ++i < n) isRect &= (twoDimArray[i].length == m); ret1urn isRect; }

126  1992-2007 Pearson Education, Inc. All rights reserved. 126 Adding two matrisis a and b Part of the My2DimArray class Called on an objcet add the instance variable to the parameter of the method

127  1992-2007 Pearson Education, Inc. All rights reserved. 127 public int[][] add(int b[][]) { int n = twDimArray.length; int m = twoDimArray[0].length; int[][] c = new[n][m]; for (int i =0 ; i < n ; i++) for (int j =0 ; j < m ; j++) c[i][j] = twoDimArray[i][j] + b[i][j]; return c; } // end of method

128  1992-2007 Pearson Education, Inc. All rights reserved. 128 Exercise Write a method of the My2DimArray class for matrix multiplication – Check the dimensionality condition for the two matrisis and if the are not appropriate return a null reference

129  1992-2007 Pearson Education, Inc. All rights reserved. 129 public class twoDimArrayTest { public static void main(String args[]) { int[][] a = {{2,4,6}, {5,1,7}}; TwoDimArray my2Dim = new TwoDimArray(a); }

130  1992-2007 Pearson Education, Inc. All rights reserved. 130

131  1992-2007 Pearson Education, Inc. All rights reserved. 131 7.10 Case Study: Class GradeBook Using a Two-Dimensional Array Class GradeBook – One-dimensional array Store student grades on a single exam – Two-dimensional array Store grades for a single student and for the class as a whole

132  1992-2007 Pearson Education, Inc. All rights reserved. 132 Outline GradeBook.java (1 of 7) Line 7 Line 10 Declare two-dimensional array grades GradeBook constructor accepts a String and a two-dimensional array

133  1992-2007 Pearson Education, Inc. All rights reserved. 133 Outline GradeBook.java (2 of 7)

134  1992-2007 Pearson Education, Inc. All rights reserved. 134 Outline GradeBook.java (3 of 7) Lines 58-67 Loop through rows of grades to find the lowest grade of any student

135  1992-2007 Pearson Education, Inc. All rights reserved. 135 Outline GradeBook.java (4 of 7) Lines 79-88 Lines 94-104 Loop through rows of grades to find the highest grade of any student Calculate a particular student’s semester average

136  1992-2007 Pearson Education, Inc. All rights reserved. 136 Outline GradeBook.java (5 of 7) Lines 115-119 Calculate the distribution of all student grades

137  1992-2007 Pearson Education, Inc. All rights reserved. 137 Outline GradeBook.java (6 of 7)

138  1992-2007 Pearson Education, Inc. All rights reserved. 138 Outline GradeBook.java (7 of 7)

139  1992-2007 Pearson Education, Inc. All rights reserved. 139 Outline GradeBookTest.java (1 of 2) Lines 10-19 Declare gradesArray as 10- by-3 array Each row represents a student; each column represents an exam grade

140  1992-2007 Pearson Education, Inc. All rights reserved. 140 Outline GradeBookTest.java (2 of 2) Program output

141  1992-2007 Pearson Education, Inc. All rights reserved. 141 7.11 Variable-Length Argument Lists Variable-length argument lists – 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

142  1992-2007 Pearson Education, Inc. All rights reserved. 142 Outline VarargsTest.java (1 of 2) Line 7 Lines 12-13 Line 15

143  1992-2007 Pearson Education, Inc. All rights reserved. 143 Outline VarargsTest.java (2 of 2) Line 29 Line 31 Line 33 Program output

144  1992-2007 Pearson Education, Inc. All rights reserved. 144 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.

145  1992-2007 Pearson Education, Inc. All rights reserved. 145 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 ]

146  1992-2007 Pearson Education, Inc. All rights reserved. 146 Outline InitArray.java (1 of 2) Line 6 Line 9 Line 16 Lines 20-21 Lines 24-25 Array args stores command- line arguments Check number of arguments passed in from the command line Obtain first command-line argument Obtain second and third command-line arguments Calculate the value for each array element based on command-line arguments

147  1992-2007 Pearson Education, Inc. All rights reserved. 147 Outline InitArray.java (2 of 2) Program output Missing command-line arguments Three command-line arguments are 5, 0 and 4 Three command-line arguments are 10, 1 and 2


Download ppt " 1992-2007 Pearson Education, Inc. All rights reserved. 1 7 7 Arrays."

Similar presentations


Ads by Google