Presentation is loading. Please wait.

Presentation is loading. Please wait.

2 Array of Objects.

Similar presentations


Presentation on theme: "2 Array of Objects."— Presentation transcript:

1 2 Array of Objects

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. What are array of objects? 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.

3 2.1 Introduction 2.2 Arrays 2.3 Declaring and Creating Arrays 2.4 Examples Using Arrays 2.5 Enhanced for Statement 2.6 Array of Objcts 2.7 Passing Arrays to Methods 2.8 MyArray Class 2.9 Multidimensional Arrays 2.10 Case Study: Class GradeBook Using a Two-Dimensional Array 2.11 Variable-Length Argument Lists

4 2.1 Introduction Arrays Data structures
Related data items of same type Remain same size once created Fixed-length entries

5 2.2 Arrays Array Group of variables Have same type Reference type

6 Fig. 7.1 | A 12-element array.

7 2.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 Common Programming Error 2.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 2.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 2.3 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 statementD c refers to a 12 integer element array Default initial values 0 for numerial variables: false for boolean null for reference types

11 2.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 Common Programming Error 2.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 2.3 Declaring and Creating Arrays (cont.)
Declaring arrays Creating arrays Initializing arrays Manipulating array elements

14 2.3 Declaring and Creating Arrays (cont.)
Creating and initializing an array Declare array Create array Initialize array elements

15 Outline Create 10 ints for array; each int is initialized to 0 by default Declare array as an array of ints 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 array.length returns length of array Each int is initialized to 0 by default array[counter] returns int associated with index in array

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 { int array[]; // declare array named array 9 array = new int[ 10 ]; // create the space for array 11 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings 13 // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); 17 } // end main 18 } // end class InitArray

17 7.3 Declaring and Creating 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 Outline Declare array as an array of ints
Compiler uses initializer list to allocate array InitArray.java Line 9 Declare array as an array of ints Line 9 Compiler uses initializer list to allocate array Program output

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 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value 14 for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); 16 } // end main 17 } // end class InitArray

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 2.4 Examples Using Arrays (Cont.)
Calculating a value to store in each array element Initialize elements of 10-element array to even integers

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 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 ] = * counter; System.out.printf( "%s%8s\n", "Index", "Value" ); // output each array element's value System.out.printf( "%5d%8d\n", counter, array[ counter ] );

24 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.

25 Common Programming Error 2.4
Assigning a value to a constant after the variable has been initialized is a compilation error.

26 Common Programming Error 2.5
Attempting to use a constant before it is initialized is a compilation error.

27 Getting the elements of an array from
The user

28 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

29 2.4 Examples Using Arrays (Cont.)
Summing the elements of an array Array elements can represent a series of values We can sum these values

30 Outline SumArray.java Line 8 Declare array with initializer list Lines Sum all array values Program output

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

32 2.5 Enhanced for Statement
Iterates through elements of an array or a collection without using a counter Syntax for ( parameter : arrayName ) statement

33 Outline EnhancedForTest .java

34 2.5 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 );

35 2.5 Enhanced for Statement (Cont.)
equivalent to for ( int counter = 0; counter < array.length; counter++ ) total += array[ counter ]; Usage and limitations Can only access array elements (read only) can appear only on the left side of assignment statments in the body of the loop Cannot modify array elements Cannot access the counter indicating the index traverese the entire array or collection cannot skip some part of the array e.g.: only even indexed elements

36 2.6 Array of Objects Array elements can refer to objects
then they are references to objects Product[] products = new[4]; products is a reference refereing to an array contaiing 4 references to objects from the Product class. after this statement elements of the products array are initilized to their default values – null no Product objects are created yet

37 2.6 Array of Objects (cont.)
after initilizing the products array with null values create Product objects and assing them to individual elements of the products array let individual elements of the products array refer to these product objects

38 class Product public class Product { private String name;
private double price; private int amount; public Product(Sting n,double p,int a) { name = n; setPrice(p); setAmount(a); } // end constructor // add set get methds } // end class Product

39 class ArrayOfObjects public class ArrayOfObjects {
public static void main(String args[]) { // create products array with 3 references to // product objects Product products = new Product[3]; // create products and attach to the array products[0] = new Product(“table”,100,10); products[1] = new Product(“chair”,75,5); products[2] = new Product(“200”,bord,3); // total value of products double total = 0.0; for(int i = 0;i< products.length;i++) total += products[i].getPrice()* products[i].getAmount(); } // end main } end class

40 Explanations treditional for loop can be converted to an enhenced for as follows: for(int e: products) total += e.getPrice()* e.getAmount(); if some of the elements of the products array are null – not assigned any products previous loops produces null pointer exceptions how to fix this potential error if(e !=null)

41 just after declaring and initilizing array
products mışş

42 just product objects created and assigned
products bord mışş table

43 2.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

44 Outline Declare 5-int array with initializer list (1 of 2) Line 9
PassArray.java (1 of 2) Line 9 Line 19 Pass entire array to method modifyArray

45 Outline Pass array element array[3] to method modifyElement
Method modifyArray manipulates the array directly PassArray.java (2 of 2) Line 30 Lines 36-40 Lines 43-48 Program output Method modifyElement manipulates a primitive’s copy

46 Example // 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 );

47 Example (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 ] "array[3] after modifyElement: %d\n", array[ 3 ] ); } // end main

48 Example (cont.) // 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

49 output Effects of passing reference to entire array:
The values of the original array are: The values of the modified array are: Effects of passing array element value: array[3] before modifyElement: 8 Value of element in modifyElement: 16 array[3] after modifyElement: 8

50 2.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

51 Performance Tip 2.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.

52 2.8 A generic array class Develop a gneric array class called MyArray
including many methods for geting arrays printing 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

53 class MyArray public class MyArray { private int[] myArray;
// constructor public MyArray(int[] theArray) myArray = theArray; // initialized elsewhere in another class // just pass the reference }

54 class MyArray – method maximum
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; }

55 class MyArray – method maxPosition
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;

56 class MyArray – method display
public void display() { for(int e: myArray) System.out.printf(“%10d”,e); }

57 class MyArray – method multiply0
public void multiply0(int k) { int n = myArray.length; // elemements of myArray are multiply by k for(int i = 0; i < n;i++) myArray[i] = myArray[i]*k; }

58 class MyArray – method multiply1
public int[] multiply1(int k) { int n = myArray.length; // a new array of the same length as myArray int[] c = new int[n]; for(int i = 0; i < n;i++) c[i] = myArray[i]*k; return c; }

59 class MyArray – method add1
public int[] add1(int[] b) { int n = myArray.length; if(b == null) return null; int m = b.length; if(n != m) // a new array of the same length as myArray and b int[] c = new int[n]; for(int i = 0; i < n;i++) c[i] = myArray[i]+b[i]; return c; }

60 class MyArray – method add2
public int[] add2(MyArray myA) { return add1(myA.myArray); }

61 class MyArray – method add13
public MyArray add3(MyArray myA) { return new MyArray(add2(myA); }

62 class TestMyArray public class TestMyArray {
public static void main(String args[]) { int[] array1 = {1,2,3}; int[] array2 = {4,5,6}; MyArray myAr1 = new MyArray(array1); MyArray myAr2 = new MyArray(array2); myAr1.display(); int max1 = myAr1.maximum(); myAr1.multiply0(3); int[] c0 = myAr1.multiply1(3); int[] c1 = myAr1.add1(array2); int[] c2 = myAr1.add2(myAr2); MyArray myAr3 = myAr1.add3(myAr2); } // end main } // end test class

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

64 Procedural approach A procedural approach for such mehods is declaring each method in the same class as arrays are defined

65 public class ArrayMetodsProcedural
{ public static void main(String args[]) int[] a = { }; int maxOfA = maximum(a); int posOfA = maxPosition(a); // print these } // end of main method

66 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

67 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

68 A generic array class Example inverting an array elements
ainv = { } 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

69 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

70 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

71 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

72 A generic array class public class InvertStatic {
public static void main(String args[]) [ int[] a = { }; 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

73 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

74 public class MyArray { int[] myArray; public MyArray(int[] myArray) this.myArray = myArray; }

75 // 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

76 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 }

77 other methods of the MyArray class
public class MyArray { int[] myArray; public MyArray(int[] myArray) this.myArray = myArray; } public void invert1() .....

78 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

79 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

80 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

81 public class MyArray { int[] myArray; // constructor and other methods

82 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++;

83 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

84 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

85 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

86 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

87 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

88 2.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

89 2.9 Multidimensional Arrays
Tables with rows and columns Two-dimensional array m-by-n array

90 Fig. 7.16 | Two-dimensional array with three rows and four columns.

91 2.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

92 2.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 } };

93 2.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

94 Outline InitArray.java (1 of 2) Line 9 Line 10

95 Outline InitArray.java (2 of 2) Line 26 Line 27 Program output

96 2.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;

97 public class My2DimArray
{ int[][] twoDimArray; // constructor public My2DimArray(int[][] newArray) twoDimArray = newArray; }

98 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

99 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

100 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}

101 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;

102 public int[] columnMax()
{ ... } public int[] rawMax() Write their columnMin and rawMin versions as well

103 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; }

104 İ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...

105 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;

106 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; }

107 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

108 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

109 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

110 public class twoDimArrayTest
{ public static void main(String args[]) int[][] a = {{2,4,6}, {5,1,7}}; TwoDimArray my2Dim = new TwoDimArray(a); }

111

112 2.10 Case Study: Class GradeBook Using a Two-Dimensional Array
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

113 Outline Declare two-dimensional array grades (1 of 7) Line 7 Line 10
GradeBook.java (1 of 7) Line 7 Line 10 GradeBook constructor accepts a String and a two-dimensional array

114 Outline GradeBook.java (2 of 7)

115 Loop through rows of grades to find the lowest grade of any student
Outline Loop through rows of grades to find the lowest grade of any student GradeBook.java (3 of 7) Lines 58-67

116 Outline Loop through rows of grades to find the highest grade of any student GradeBook.java (4 of 7) Lines 79-88 Lines Calculate a particular student’s semester average

117 Calculate the distribution of all student grades
Outline GradeBook.java (5 of 7) Lines Calculate the distribution of all student grades

118 Outline GradeBook.java (6 of 7)

119 Outline GradeBook.java (7 of 7)

120 Each row represents a student; each column represents an exam grade
Outline Declare gradesArray as 10-by-3 array GradeBookTest.java (1 of 2) Lines 10-19 Each row represents a student; each column represents an exam grade

121 Outline GradeBookTest .java (2 of 2) Program output

122 2.11 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

123 Outline VarargsTest .java (1 of 2) Line 7 Lines 12-13 Line 15

124 Outline (2 of 2) Line 29 Line 31 Line 33 Program output VarargsTest
.java (2 of 2) Line 29 Line 31 Line 33 Program output

125 Common Programming Error 2.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.


Download ppt "2 Array of Objects."

Similar presentations


Ads by Google