Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10 The One-Dimensional Array Section 1 - What is a One-Dimensional Array? Section 2 - Declaring and Instantiating an Array Section 3 - The Power.

Similar presentations


Presentation on theme: "Chapter 10 The One-Dimensional Array Section 1 - What is a One-Dimensional Array? Section 2 - Declaring and Instantiating an Array Section 3 - The Power."— Presentation transcript:

1

2 Chapter 10 The One-Dimensional Array Section 1 - What is a One-Dimensional Array? Section 2 - Declaring and Instantiating an Array Section 3 - The Power of Loops with Arrays Section 4 - Array Physical and Logical Sizes Section 5 - Initializer Lists Section 6 - Arrays are Objects Section 7 - Using Arrays in Methods Section 8 - Class Variables, Constants, & Methods Section 9 - Enhanced For Loops Section 10 - Arrays of Other Objects Section 11 - Removing and Adding Elements from an Array Section 12 - Unified Modeling Language (UML) Diagrams Go 1

3 Chapter 10 - Section 1 What is a One-Dimensional Array? 2

4 10.1 Objectives of this Chapter Understand what a one-dimensional array is and what its advantages are. Declare array variables and instantiate array objects. Write programs that handle lists of similar items stored in arrays. Manipulate arrays with loops, including the enhanced for loop. Write methods to manipulate arrays. 3

5 10.1 Array Vocabulary Array Element Enhanced for loop Index Subscript Subscript operator [ ] Initializer list One-dimensional array Logical size Physical size Parallel arrays Ragged array Range-bound error Structure chart 4

6 10.1 Visualizing a One-Dimensional Array Java provides a data structure called an array. Arrays are a contiguous block of memory locations that can be referred to with one variable like nums. Here is an array that holds random integers. [0] [1] [2] [3] [4] [5] [6] [7] The value 7 is stored at index 0 the first memory location of the array. The value 4 is stored at index 1 the second memory location of the array. The value 9 is stored at index 2 the third memory location of the array. and so on. 74916385 nums 5

7 10.1 What is an Array? An array is a collection of similar data values that are stored in contiguous RAM memory locations. Contiguous means the memory locations are all adjacent to one another without any gaps. Sometimes we speak of the 48 contiguous states of the United States, because they are all touching each other with no gaps. An array has a single name, and the elements in an array are referred to in terms of their position within the array. 6

8 10.1 Arrays Make Working with Data Easier An array makes it as easy to manipulate a million test scores as it does three. Without an array, a class with 20 test scores would look like this with 20 variables declared - one for each test: public class Student { private String name; private int test1, test2, test3, test4, test5, test6, test7, test8, test9, test10, test11, test12, test13, test14, test15, test16, test17, test18, test19, test20; } 7

9 10.1 Averaging Test Scores Without an Array And the computation of the average score looks like this: public int getAverage() { int average = (test1 + test2 + test3 + test4 + test5 + test6 + test7 + test8 + test9 + test10 + test11 + test12 + test13 + test14 + test15 + test16 + test17 + test18 + test19 + test20 ) / 20; return average; } We will see how it is done more easily with an array and a loop. 8

10 10.1 Arrays Can Contain Anything The values in an array are called elements. For any particular array, all of the elements must be of the same type. They can be any primitive or any reference type: array of int array of double array of boolean array of char array of String array of Student reference types 9 primitive types

11 10.1 Example Arrays Here is how a number of different arrays of different types can be visualized: 9288958493 tests “Sue”“Tom”“Ann”“John”“Barb” names - 273.16- 42.3710.73100.0500.77 temps s1s2s3s4s5 students 10

12 10.1 Array Indices Begin at 0 An element’s position within an array is called its index or subscript. In Java, numbering starts with 0 rather than 1, so index values begin with 0. The first array memory location is identified as index 0, the second one as index 1, and so on. We use the subscript operator [ ] and an index number to reference or access the element stored in an array location. The length of an array refers to its physical size or the physical number of memory locations in the array when it was created. 11

13 Chapter 10 - Section 2 Declaring and Instantiating Arrays 12

14 10.2 Standard Array Construction Declaring and instantiating an array of 500 integers: int [ ] nums = new int [500]; This array will have index values from 0 to 499. The syntax for referring to an array element is: nums [index] An index must be between 0 and the array’s length minus 1 … if there are n items, then the index values can be from 0 to n - 1. Here we could refer to nums[0], nums[1], nums[2], … nums[499], but not nums[500]. Once instantiated, the size of an array is fixed and cannot be changed. This is a small disadvantage of arrays. physical size in the [ ] 13

15 10.2 Alternate Array Declarations We’ve learned that to declare an array you use … int [ ] nums; If we use only this line of code, then nums will reference null. This is because arrays are actually objects and no memory has been allocated for the array through construction. It would be the same if we used Student s1; then s1 would reference null, since it is an object variable. 14

16 10.2 Default Values for an Array of Ints If we declare the array nums as follows int [ ] nums = new int [10]; then nums doesn’t reference null. It references a contiguous block of memory and all array elements are initialized to 0 by default since the array will contain primitive int values. 15 00000000 nums

17 10.2 Default Values for an Array of Doubles If we declare the array temps as follows double [ ] temps = new double [15]; then temps doesn’t reference null and all array elements are initialized to 0.0 since the array will contain primitive double values. 16 0.0 temps

18 10.2 Default Values for an Array of Strings However, if we declare and instantiate the following array … String [ ] names = new String [20]; then names doesn’t reference null but all the array elements are initialized to null by default … NOT empty string … “” like you might think. The reason is no valid String objects have been placed in the array locations. Similarly, if we declare a String variable, but don’t initialize it to a String value, then it references null. Example: String name; // name references null 17 null names

19 10.2 Reminder of Empty String Note: empty string has no character inside the double quotes. Not even a blank space! However, it is a valid value but it is not the same as null. We have previously initialized a String variable to empty string. The variables in the following two lines of code reference different values. String name; // name references null String sport = “”; // sport references empty string 18

20 10.2 The Physical Size of an Array A standard array has a public variable or field named length that yields the physical size of the array. The physical size is how large the array has been instantiated to be. So if the array was declared as … int [ ] nums = new int [500]; then the physical size is 500 and the line of code: System.out.println(“Physical size is ” + nums.length); would output: Physical size is 500 Note: there are no ( ) with length! 19

21 10.2 Precedence of the Subscript Operator The subscript operator [ ] has the same precedence as the method selector (. ) 20

22 10.2 Storing Values in an Array Values are stored in an array using the assignment operator, just like you would any other variable and you have to indicate which memory location you wish to store in by using the subscript operator and an index value: int [ ] nums = new int [500]; nums [0] = (int)(Math.random() * 100) + 1; nums [1] = (int)(Math.random() * 100) + 1; nums [2] = (int)(Math.random() * 100) + 1; …… nums [499] = (int)(Math.random() * 100) + 1; 21

23 10.2 Accessing Values in an Array Values in an array are accessed by using the subscript operator and an index value. The values can then be printed or used in some other operation: System.out.println(“The value at index 0 is: ” + nums[0]); System.out.println(“The value at index 1 is: ” + nums[1]); ….. double ave = (double) ( nums[0] + num[1] ) / 2; Also … if ( nums[0] % 2 == 0) is a legal Java expression. 22

24 10.2 The ArrayIndexOutOfBoundsException The JVM checks the value of an array index before accessing it and throws an exception of type… ArrayIndexOutOfBoundsException if the index is out of bounds. Based on the previous array declaration … nums[-1] = 48; nums[500] = 48; would both throw an ArrayIndexOutOfBoundsException. 23

25 10.2 Swapping Elements in an Array Two elements in an array can be swapped using the following code: int temp = nums[0]; nums[0] = nums[1]; nums[1] = temp; 24

26 10.2 Simple Array Manipulations Assume that the array a contains the 5 integers: 34, 23, 67, 89, and 12 in that order. What values are represented by the following expressions? a[1] = a[a.length-1] = a[2] + a[3] = 25

27 10.2 Simple Array Manipulations Assume that the array a contains the 5 integers: 34, 23, 67, 89, and 12 in that order. What values are represented by the following expressions? a[1] = 23 a[a.length-1] = 12 a[2] + a[3] = 67 + 89 = 156 26

28 Chapter 10 - Section 3 The Power of Using Loops with Arrays 27

29 10.3 Looping Through Arrays Using a loop to iterate through each element in an array is a common task. – The loop control variable is used as the array index inside the subscript operator – Example applications: Store values in the elements of an array Print the values in the elements of an array Sum the values in the elements of an array Search for a value in the elements of an array Count occurrences of a value in an array 28

30 10.3 Looping Through Arrays In our previous example of using the array nums that was declared and instantiated as: int [ ] nums = new int [500]; It is better to use nums.length in our code rather than 500. Using length makes the code generic so that other code doesn’t have to be changed later if we change the size of the array. We will want to do this whenever we have a loop. We want to make the code generic. for ( int i = 0; i < nums.length; i ++) // don’t use 500 ……. // note the use of < not <= 29

31 10.3 Assignment Statements Used to Store 30 An assignment statement is used to store values in an array. On the left side of the assignment statement, we designate the array memory location where we want to store a value. On the right side of the assignment statement, is the value to be stored in the array location. The value can be a literal value, like 123, or an arithmetic expression that produces a value, or you can ask for a value from the keyboard. So if we have nums declared as on the previous slide as: int [ ] nums = new int [500]; then we can use … nums[0] = 123; nums[1] = 5 * 14 - 12 / 4; nums[2] = (int) (Math.random() * 10) + 1; nums[3] = reader.nextInt(); array memory locations designated on the left side values to be stored on the right side.

32 10.3 Storing Values in an Array From Keyboard Scanner reader = new Scanner (System.in); int [ ] nums = new int [20]; for ( int i = 0; i < nums.length; i ++) // note the use of < not <= { System.out.print(“Enter an integer: ”); nums[i] = reader.nextInt(); } Here i is the loop control variable and represents the array index during each iteration of the loop. The letter i is a nice loop control variable name as it seems to infer index. 31 It is important to initialize i to zero not 1, because the first element of an array is at index zero!

33 10.3 Storing Random Values in an Array OR storing random integers between 1 and 1000 inclusive in the array … for ( int i = 0; i < nums.length; i ++) { nums[i] = (int) (Math.random() * 1000) + 1; } 32

34 10.3 Printing Values in an Array To print all of the values in the array nums all on one line with two spaces between each value we could use: for ( int i = 0; i < nums.length; i ++) // note the use of < not <= { System.out.print (nums[i] + “ ”); // use print not println } Again i is the loop control variable and represents the array index on each iteration of the loop. This is why i must start at 0 and we use < instead of <= so we don’t get an exception. 33

35 10.3 Printing Values in an Array with Printf To use a count up for loop that will print all of the random integers in nums one per line right justified in a field width of 6 … System.out.println("Here are the 10 random integers."); for ( int i = 0; i < nums.length; i ++) { System.out.printf("%6d%n", nums[i]); } 34

36 10.3 Printing Values in an Array with Printf To use a count up for loop that will print all of the random integers in nums on one line right justified in a field width of 6 … System.out.println("Here are the 10 random integers."); for ( int i = 0; i < nums.length; i ++) { System.out.printf("%6d", nums[i]); // don’t include %n } System.out.println(); // start a new line after outputting the numbers. 35

37 10.3 Printing Values in an Array in Reverse To print the values in the array nums in reverse all on one line with two spaces between each value : for ( int i = nums.length - 1; i >= 0 ; i --) { System.out.print (nums[i] + “ ”); } Again i is the loop control variable and represents the array index on each iteration of the loop. 36

38 10.3 Printing Values in an Array with Printf To use a count up for loop that will print all of the random integers in nums five per line right justified in a field width of 6. System.out.println("Here are the 10 random integers."); int count = 1; for ( int i = 0; i < nums.length; i ++) { System.out.printf("%6d", nums[i]); if (count % 5 == 0) System.out.println(); // start a new line count++; } 37

39 10.3 Printing Values in an Array with Printf To use a count down for loop that will print all of the random integers in nums one per line right justified in a field width of 6. System.out.print(“Here are the 10 random integers in” ); System.out.print(“ reverse order: ”); for ( int i = nums.length - 1; i >= 0 ; i--) { System.out.printf(“%6d%n”, nums[i]); } 38

40 10.3 Summing the Values in an Array We could sum the values in the array by using: int sum = 0; for ( int i = 0; i < nums.length; i ++) { sum += nums[i]; } Again i is the loop control variable and is used as the array index on each iteration of the loop. 39

41 10.3 Averaging Test Scores With an Array And now computing the average score would look like this: int sum = 0; for ( int i = 0; i < tests.length; i ++) { sum += tests[i]; } double average = (double) sum / tests.length; System.out.println(“The average is: ” + average); 40

42 10.3 Summing Odd Values in an Array To write a for loop that will sum the values of only the odd random integers in the array nums. The sum should be printed after the loop is over. int sum = 0; for ( int i = 0; i < nums.length; i ++) { if (nums[i] % 2 == 1) { sum += nums[i]; } System.out.println("The sum of the odd integers in nums is: " + sum); 41

43 10.3 Searching for a Value in an Array boolean found = false; System.out.print(“Enter an integer to search for: ”); int x = reader.nextInt(); for ( int i = 0; i < nums.length; i ++) { if (nums[i] == x) // use == if the array holds primitives { found = true; break; } if (found) System.out.println(“Found!”); else System.out.println(“NOT Found!”); 42

44 10.3 Finding the Location of a Value in an Array int loc = -1; int x = reader.nextInt(); for ( int i = 0; i < nums.length; i ++) { if (nums[i] == x) // use == if the array holds primitives { loc = i; break; } if (loc == -1) System.out.println(“NOT Found!”); else System.out.println(“Found at index ” + loc); 43

45 10.3 Counting a Value in an Array Determine how many times x occurs in the array nums: int x = reader.nextInt(); int count = 0; for ( int i = 0; i < nums.length; i ++) { if (nums[i] == x) // use == if the array holds primitives count++; } System.out.println( x + “ occurs ” + count + “ times!”); 44

46 10.3 Copying Arrays The values in one array can be copied to another array using a loop: double [ ] abc = new double [10]; // an array is constructed for abc for ( int i = 0; i < 10; i ++) abc [i] = Math.random() * 10; double [ ] xyz = new double [10]; // an array is constructed for xyz for ( i = 0; i < 10; i ++) xyz [i] = abc [i]; // each value in abc is being copied to xyz. abc = null;// abc no longer references the original array 45

47 10.3 Revamping the Student Class Here is how we could revamp the Student class to handle 20 test scores by changing the instance variables and the default constructor: public class Student { private String name; private int [ ] tests; public Student ( ) { name = “”; tests = new int [20]; for (int i = 0; i < tests.length; i++) { tests[i] = 0; } 46

48 10.3 Revamping the Student Class Changes to the initializing constructor: public Student (String nm, int [ ] t ) { name = “”; tests = new int [20]; for (int i = 0; i < tests.length; i++) { tests[i] = t[i] ; } 47

49 10.3 Revamping the Student Class Changes to the getAverage() method: public double getAverage () { double sum = 0; for (int i = 0; i < tests.length; i++) { sum += tests[i]; } double average = sum / tests.length; return average; } 48

50 Chapter 10 - Section 4 Array Physical and Logical Sizes Adding Values to an Array Removing Values from an Array 49

51 10.4 Physical & Logical Size of Arrays Physical size: The maximum number of elements that an array can contain. This is the size the array has when it is instantiated. int [ ] nums = new int [50]; For example, the physical size of the array is 50 for the array nums. Logical size: the actual number of elements stored in the array by a program. Let’s say 35 numbers have been stored, then as far as the application is concerned, 15 of the storage locations contain garbage and the logical size is 35. However, we must keep track of the logical size or we might access a portion of the array that has invalid values. 50

52 10.4 Processing an Array with the Logical Size int [] nums = new int[50]; int count = 0; // this variable will track the logical size nums[0] = 5; count++; Nums[1] = 10; count++; // more adds and incrementing count after each add int sum = 0; for (int i = 0; i < count ; i++) // Use count instead of nums.length sum += nums[i]; This loop only adds the data in the valid part of the array that is indicated by the logical size. 51

53 10.4 Tracking the Logical Size of an Array So now we know that when arrays that are not full, the programmer must track the logical array size. To do this: – Declare an integer counter variable that will keep track of the number of elements, like count. – Adjust the counter variable up or down every time an element is added or removed. – The counter will track the logical size and indicate the next open position in the array where a new value can be added. We are using evenCount, oddCount, and negativeCount to do this in the RandomIntProcessor program. 52

54 10.4 Partially Filling an Array with a Loop After declaring and instantiating an array, we may want to let the user enter as many values as they want from the keyboard. In this case, we should use a while loop that depends on two conditions: String doItAgain = “y”; int numberOfPlayers = 0; while (doItAgain.equals(“y”) && numberOfPlayers < players.length) { // code to ask the user for a player’s data // code to construct a BBallPlayer object from the data // code to add the BBallPlayer object to the array at position numberOfPlayers // increment the logical size of the array by one System.out.print(“Enter another player? (y/n): ”); doItAgain = reader.nextLine(); } 53

55 10.4 Adding at the Logical Size On the previous slide, numberOfPlayers holds the value of the next “empty” or “available” place to put a player in the array. You just need to make sure that the array is not full before you do this … in other words make sure that if you are using a loop that you have while (doItAgain.equals(“y”) && numberOfPlayers < players.length) 54

56 10.4 Passing an Array to a Method We can pass an array to a method and work with the array in it. Write the method printNames. It does not return a value. It receives two parameters... the first is the String array names and the second is an integer parameter numberOfNames representing the logical size of the names array. The method will contain a loop that will print only the names in the valid part of the array. Do NOT print any default values stored in the unused portion of the array. Print only one name per line with no other information. public static void printNames(String [ ] names, int numberOfNames) { for (int i = 0; i < numberOfNames; i++) { System.out.println(names[i]); } } // end printNames You will do something like this on the BBallTeamDriver Program. 55

57 10.4 Adding Elements to an Array When we add an element to an array, we want to make sure that we always place it immediately after the last added item. If we don’t do this then we will have gaps in our data!!! Before we add, we must first check to see if the array is full and if it isn’t then we can add a data value and then remember to increment the array's logical size by one. The code on the next slide does this …. 56

58 10.4 Adding Elements to an Array if (count < nums.length) { nums[count] = anInt; count++; } When count equals nums.length, the array is full so the if will not be executed. The if statement prevents a bounds error from occurring. Remember that Java arrays are of fixed size when they are instantiated, so eventually they may become full. 57

59 10.4 Removing Elements from an Array Removing a data element from the end of an array requires no change to the array itself. We simply decrement the logical size! 749 1 6 0 0 0 [0][1][2][3][4][5][6][7] 58 If we have 5 valid values in the array so that the logical size is 5, then to remove the value 6 we decrement the logical size to 4, but 6 is still actually in the array but won’t be processed if we use the logical size to print data or access it in some way!

60 10.4 Removing Elements from an Array If we use logical size in all operations that process the array (like printing) then 6 will never be processed. The logical size prevents the program from accessing the invalid elements beyond the valid portion of the array. Later if we add a new value it will overwrite 6. 59

61 10.4 Removing Elements from an Array What needs to happen to the array when we remove an element in the middle of the portion of the array that has valid values? 60

62 10.4 Removing Elements from an Array What needs to happen to the array when we remove an element in the middle of the portion of the array that has valid values? To remove 9 we copy 1 and overwrite 9, then we copy 6 overwrite 1 and then decrement the logical size by 1. This is essentially shifting the values down. 749 1 6 0 0 0 [0][1][2] [3] [4] [5] [6] [7] 741 6 6 0 0 0 [0][1][2] [3] [4] [5] [6] [7] Before After Note the 6 at index 4 is now in the invalid part of the array. 61

63 Chapter 10 - Section 5 Initializer Lists 62

64 10.5 Initializer Lists Arrays can be declared, instantiated, and initialized using an initializer list. int [ ] nums = {1, 2, 3, 4, 5}; Notice the new operator is NOT used and also square brackets [ ] are not used on the right side of the code. The values are separated by commas and enclosed in curly braces { } NOT [ ]. 63

65 10.5 Remember fillPolygon??? When you used the line … int x [ ] = {10, 40, 60, 30, 40}; you declared this array using an initializer list … and a similar one for … int y [ ] = {25, 25, 50, 60, 40}; g.fillPolygon(x, y, 5); You were actually making two parallel arrays, where the first element in the x array was associated with the first element in the y array and similarly for the remainder of the elements. 10 40 60 30 40 [0] [1] [2] [3] [4] 64 25 25 50 60 40 [0] [1] [2] [3] [4]

66 10.5 Initializer Lists Examples An array of int values: int [ ] nums = {1, 2, 3, 4, 5}; This is short cut code for doing the six lines of code: int [ ] nums = new int [5]; nums [0] = 1; nums [1] = 2; nums [2] = 3; nums [3] = 4; nums [4] = 5; 65

67 10.5 Initializer Lists Examples An array of double values: double [ ] xyz = {1.705, 2.38, 3.59, 4.6, 5.33}; This is short cut code for doing the six lines of code: double [ ] xyz = new double [5]; xyz[0] = 1.705; xyz[1] = 2.38; xyz[2] = 3.59; xyz[3] = 4.6; xyz[4] = 5.33; 66

68 10.5 Initializer Lists Examples An array of String values: String [ ] names = {“Sue”, “Bill”, “Ann”, “Tom”}; This is short cut code for doing the five lines of code: String[ ] names = new String [4]; names[0] = “Sue”; names[1] = “Bill”; names[2] = “Ann”; names[3] = “Tom”; 67

69 10.5 Operations on Initializer Lists Arrays that are declared, instantiated, and initialized using an initializer list are treated exactly the same as arrays declared and instantiated in the standard way. There is no difference if they are passed to methods or returned by methods. The only difference is in the way they are declared and instantiated. 68

70 Chapter 10 - Section 6 Arrays are Objects 69

71 10.6 Arrays are Objects When you use the following line of code … double [ ] temps = new double [20]; you are doing two things: 1. declaring an array variable named temps that can hold floating-point values (This is just a variable that points at the array. It is not the array itself!) 2. creating an array object with the specified number of memory locations. It can be done in two separate lines of code … double [ ] temps; // declaring temps but not instantiating so temps points // at null (nothing). However, null is a valid object value. temps = new double [20]; // instantiating temps 70

72 10.6 Instantiating Arrays Arrays are objects and must be instantiated before being used. Otherwise you get a NullPointerException. Declare nums: int[] nums; Instantiation nums: nums = new int[5]; Its ok to write these lines of codes separately but generally we do it all in one line of code. One place where you would want to do it separately is when the array variable is an instance variable and then you would instantiate it in the constructor. 71

73 10.6 Forgetting to Instantiate the Array A NullPointerException occurs with the following two lines of code, because the array variable nums is declared but not instantiated: int [ ] nums; // array declared but not instantiated nums[0] =10; // throws a NullPointerException 72

74 10.6 Arrays are Objects All rules that apply to objects apply to arrays. Note these details: – Two array variables may refer to the same array, but it is usually not a good idea. If two variables do, then one is an alias. – An array is sent to garbage collection if no array variable references it. This would be the case if the variable is set to null. – Array variables may be set to null if you don’t want to instantiate them or if you want to destroy the data by pointing the variable away from the memory locations … nums = null; Remember: null is not the same thing as zero. – Arrays are passed by reference to methods. This means that a reference (alias) is passed to the method, not a copy of the array. The reference has full access to the array in the method. 73

75 10.6 Aliases with Arrays Here, variable xyz never has an array constructed for it to refer to. int [ ] abc, xyz; abc = {2, 4, 6, 8};// an array is constructed for abc but NOT xyz xyz = abc;// xyz is an alias to the array referred to by abc xyz [3] = 100;// this line of code overwrites 8 with 100 System.out.println (abc [3] ); // 100 is printed because 8 is gone. The line of code xyz = abc; does NOT make a copy of the array! It only makes xyz an alias, so that xyz points at the same array abc points at. Note that array variable xyz is never instantiated. Unless it is absolutely necessary don’t create aliases in a program. Everything will be easier. 74

76 10.6 Visualizing Arrays Two array variables can refer to the same array object and the line of code xyz[3] = 100; changes the value at index 3, since xyz has access to the array, not just abc. abc is the original variable that refers to the array. xyz is the alias that refers to the array, because of the line of code xyz = abc. 75 abcxyz 2468 246100

77 10.6 Parallel Arrays Two or more arrays of the same size that store associated data are called Parallel Arrays. String [ ] names = { “Bill”, “Sue”, “Shawn”, “Mary”, “Ann” }; int [ ] ages = { 20, 21, 19, 24, 20 }; Here one array contains names and a second contains corresponding ages. Here Bill and 20 are associated, as are Sue and 21, Shawn and 19, Mary and 24, and Ann and 20. 76

78 Chapter 10 - Section 7 Using Arrays in Methods 77

79 10.7 Passing Arrays to Methods Because arrays are objects, they are passed by reference to methods. This means that the actual and formal parameters refer to the same array and a copy of the array is not made. The formal parameter is an alias of the actual parameter and whatever changes you make using the formal parameter in the method are retained by the actual parameter when the method is over. The important point is that the method manipulates the original array, not a copy of the array and changes to the array made in the method are retained after the method is complete. 78

80 10.7 Method that Prints an Array of Ints This method has an array passed to it so the array can be printed. It’s convenient to have a method that can be called many times like this one. You wouldn’t want to have to stop and write the code that is in this method over and over again whenever values need to be printed. public static void printIntArray(int [ ] array) { for ( int i = 0; i < array.length; i++) System.out.print(array[ i ] + “ ”); } 79

81 10.7 Calling a Void Method The printIntArray method is a void method. Whenever, you call a void method you don’t use an assignment statement. You just use the name of the method and pass it what it needs. public static void main (String [ ] args) { int [ ] nums = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 }; printIntArray(nums); <---- VOID Method Call } public static void printIntArray(int [ ] array) { for ( int i = 0; i < array.length; i++) System.out.print(array[ i ] + “ ”); } 80

82 10.7 Correct Printing of 10 Values Per Line When an array has a large number of values that need to be printed, it makes sense to use a printf statement and organize the output so it is readable. Besides the printf statement spacing out the values, we can control how many values are printed per line. Here is an example that prints 10 values per line with each value in a field width of 5. Note where %n is located that starts a new line. public static void printIntArray(int [ ] array) { int count = 1; for ( int i = 0; i < array.length; i++) { if (count % 10 == 0) System.out.printf(“%5d%n”, array[ i ]); else System.out.printf(“%5d”, array[ i ]); count++; } 81

83 10.7 Incorrect Printing of 10 Values Per Line Note this version of the method prints the values incorrectly. It prints the first value and then immediately starts a new line, because 0 % 10 is equal to zero. public static void printIntArray(int [ ] array) { int count = 0; // need to start count at 1 not 0 for ( int i = 0; i < array.length; i++) { if (count % 10 == 0) System.out.printf(“%5d%n”, array[ i ]); else System.out.printf(“%5d”, array[ i ]); count++; } 82

84 10.7 Calling Methods that Return a Value This method has an array passed to it and the values will be summed and the sum will be returned. public static void main (String [ ] args) { int [ ] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sumOfNums = sum(nums); System.out.println(“The sum is ” + sumOfNums ); } public static int sum(int [ ] array) { int total = 0; for ( int i = 0; i < array.length; i++) total += array[i]; return total; } nums is the actual parameter and array is the formal parameter, so array is an alias of nums. Methods that return a value must be called using an assignment statement or the value returned is lost. Here sumOfNums “catches” the returned value. 83

85 10.7 A Method that Modifies an Array This method has an array passed to it and the values will be modified. The odd values in the array will be multiplied by 2 and placed back in the array. public static void main (String [ ] args) { int [ ] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; multiplyOddsByTwo(nums); printNums(nums); // the values printed are 2, 2, 6, 4, 10, 6, 14, 8, 18, 10 } public static void multiplyOddsByTwo(int [ ] array) { for ( int i = 0; i < array.length; i++) if (array [ i ] % 2 == 1) array[i] = array[i] * 2; } Here the alias array has modified the original array!! 84 The formal parameter array is an alias of nums.

86 10.7 Passing Arrays to Methods Passing arrays by reference to a method is efficient because Java doesn’t have to stop and make a copy of the array. If arrays weren’t passed by reference, then we would have to worry about how to get the changes in a copy of the array reflected back into the original array. So it is good that the changes to values in an array are preserved when a method is over, because the formal parameter is an alias of the actual parameter. 85

87 10.7 Calling Methods that Return a Value Notice that this method is written to sum an array of any size. public static void main (String [ ] args) { int [ ] array1 = { 10, 24, 16, 78, -55, 89, 65 }; int [ ] array2 = { 4334, 22928, 33291 }; if (sum(array1) > sum(array2)) System.out.println(“The sum of array1 is larger”); } public static int sum(int [ ] array) { int total = 0; for ( int i = 0; i < array.length; i++) total += array[i]; return total; } // array1 & array2 are actual parameters in the call of the sum method Its important to write methods so they work with any size array. 86

88 10.7 Letting a Method Fill an Array public static void main (String [ ] args) { int [ ] nums = new int [10]; fillArray(nums); } public static void fillArray (int [ ] numbers) { Scanner reader = new Scanner (System.in); for (int i = 0; i < numbers.length; i++) { System.out.print(“Enter an integer: ”); numbers[ i ] = reader. nextInt(); } 87 Notice that this method is written to fill an empty array. The formal parameter numbers is an alias of the original actual array parameter nums. Modifying the array using numbers modifies the original array named nums, so we don’t need to construct an array here inside the method.

89 10.7 Letting a Method Fill an Array by Query public static int fillArray (int [ ] numbers) { Scanner reader = new Scanner (System.in); int count = 0; String ans = “y” while ( count < numbers.length && ans.equals(“y”) ) { System.out.print(“Enter an integer: ”); numbers[count] = reader.nextInt(); count++; System.out.print(“Run it again? Type y – yes or n – no”); ans = reader.nextLIne(); } return count; } 88

90 10.7 A Method that Searches an Array We can pass an array and a search value to a method to see if a value exists in the array. Because this process may need to be done many times in a program, it makes sense to write the code once and place it in a method. Then, the method can be called whenever it is needed. public static int search(int [ ] a, int searchValue) { for ( int i = 0; i < a.length; i++) if (a[i] == searchValue) return i; return -1; } 89

91 10.7 Methods Can Instantiate & Return an Array A method can also instantiate an array and return it. When this is the case, the calling method usually has an array variable that has been declared but NOT instantiated. The array variable is then assigned the array that is returned. We could also say the array variable “catches” the array returned by the method. The next slide has an example. 90

92 10.7 A Method that Returns an Array Here the method getFriends creates, fills, and returns an array. public static String [ ] getFriends ( int numberOfFriends) { Scanner reader = new Scanner (System.in); String [ ] friends = new String [numberOfFriends]; for ( int i = 0; i < friends.length; i++) { System.out.print(“Enter a friend’s name: ”); friends [i] = reader.nextLine(); } return friends ; } 91 An array of String is returned.

93 10.7 Methods that Return an Array In the main method, the array buddies is declared but not instantiated. This array “catches” the array returned by the method getFriends in the assignment statement below. The method needs an int value passed to know how big to make the array it will return, so we pass it numberOfFriends. When we say “catch”, we mean the array returned by the method is is also referenced by the array variable buddies. String [ ] buddies ; // array declared but not instantiated System.out.print(“Enter the number of friends: ”); int numberOfFriends = reader.nextInt(); buddies = getFriends (numberOfFriends ); 92

94 10.7 Calling the getFriends Method public static void main (String [ ] args) { String [ ] buddies; // array declared but not instantiated System.out.print(“Enter the number of friends: ”); int numberOfFriends = reader.nextInt(); buddies = getFriends (numberOfFriends); } public static String [ ] getFriends ( int numberOfFriends) { Scanner reader = new Scanner (System.in); String [ ] friends = new String [numberOfFriends]; for ( int i = 0; i < friends.length; i++) { System.out.print(“Enter a friend’s name: ”); friends [i] = reader.nextLine(); } return friends; // when returning array don’t use [ ] just the name of the array } Here is all the code together. Note the call of the getFriends() method in an assignment statement. 93

95 10.7 Passing Arrays to Methods You need to be aware of an erroneous approach to passing arrays to methods. It happens because a void method tries to instantiate an array inside of it and make a parameter to the method reference it. First, we’ll look at the erroneous code and what happens when it is used and then we’ll look at the proper approach and see why it works. 94

96 10.7 Incorrect copyArray( ) method Here is an example of how a method should not be used to manipulate an array. In the main() method, we have a void method call: int [ ] orig = {1, 2, 3, 4, 5}; int [ ] cp; copyArray (orig, cp); public static void copyArray (int [ ] original, int [ ] copy) { copy = new int [original.length]; // instantiate for (int i = 0; i < original.length; i++) { copy [ i ] = original[ i ]; } Because cp was not instantiated before the method call, instantiating its alias named copy in the method and filling it is not enough to make the changes permanent when the method is over. If you tried to print out the contents of cp in main after the method call you would get a null-pointer exception. 95 The alias of the un- instantiated array cp is copy. Making a void method call and passing it an instantiated array orig and a non-instantiated array cp.

97 10.7 Correct copyArray( ) method … in main() method … int [ ] orig = {1, 2, 3, 4, 5}; int [ ] cp = copyArray (orig); // make a copy of orig and the copy is returned public static int [ ] copyArray (int [ ] original) { int [ ] copy = new int [original.length]; // instantiate for (int i = 0; i < original.length; i++) { copy [ i ] = original[ i ]; return copy; // array is returned } 96 This approach instantiates copy in the method and returns it preserving the values. You don’t need to know why Java does it correctly this way. You just need to know that if you don’t return it, then the values won’t be preserved.

98 Chapter 10 – Section 8 Class Variables, Constants, & Methods 97

99 10.8 Instance Variables vs. Class Variables Until now we have used only instance variables and instance methods. Any instance of a class (any instantiated object or constructed object) has memory allocated for its instance variables when it is constructed. Instance methods are accessor and mutator methods that we use to access or change values in the instance variables. Now we will use class variables, class constants and class methods. They belong to a class NOT an object of the class. 98

100 10.8 Class Variables and Constants of Student Class variables, constants, and methods are declared using the keyword static. We are going to add the following to the model class Student that we have recently used: class variable: static private int studentCount; class constants: static final public int MIN_SCORE = 0; static final public int MAX_SCORE = 100; 99

101 10.8 Class Methods of the Student Class We are going to add these class methods to the Student class: // Class (static) accessor method static public int getStudentCount() { return studentCount; } // Class (static) mutator method static public void setStudentCount(int count) { studentCount = count; } 100

102 10.8 Class ( static ) Variables and Constants A class variable or class constant belongs to a class NOT an object of the class. Storage for a class variable or class constant is allocated at program startup not when an object of the class is constructed. The following are all allocated storage space during program startup: // Class (static) variable static private int studentCount; // Class (static) constants static final public int MIN_SCORE = 0; static final public int MAX_SCORE = 100; 101

103 10.8 Using the studentCount Class Variable We will use the class variable studentCount to track all the Student objects constructed during a program. This could be very helpful in a program that maintains a standard array of Student objects, because studentCount could be used to track the logical size of Student objects in the array. Using the value in studentCount to know how many times to run a loop that prints all student data, could be very helpful and it would allow us to add new students to the array in the first available location at the end of the array. 102

104 10.8 Calling the setStudentCount( ) Method Since studentCount can be used to track the logical size of a standard array, then we must initialize its value to zero at the start of a program. We can do this using the class method named setStudentCount: static public void setStudentCount(int count) { studentCount = count; } To initialize studentCount to zero, in a driver program, use the code: Student.setStudentCount(0); 103 Note the class is used to call the method, similar to Math.sqrt().

105 10.8 Incrementing studentCount Then as the driver program adds Student objects to the array by calling the Student class constructors, we can increment the logical size by incrementing studentCount in each constructor of the Student class (since we don’t know which constructor will get called). public Student(String nm) { studentCount ++; name = nm; tests = new int[3]; for (int i = 0; i < tests.length; i++) tests[i] = 0; } 104

106 10.8 Calling the getStudentCount( ) Method Since studentCount is a private class variable, we need to access its value by calling the class method named getStudentCount(). Here is how it could be done: int numberOfStudents = Student.getStudentCount(); You’ve noticed by now that we call both setStudentCount and getStudentCount by preceding the method name with the name of the class Student. This is because a class method is activated when a message is sent to the class rather than to an object. Its like calling Math.sqrt(x) or Math.pow(base, exp); 105

107 10.8 Decrementing the studenCount If we delete a Student from the array, we can update the studentCount by calling the setStudentCount method as follows: Student.setStudentCount(Student.getStudentCount() - 1); 106

108 10.8 Class Constants (final variables) Class constants, also called final variables, should be able to be used by the class they are defined in or by a driver file. Therefore, they need to be declared as public. static final public int MIN_SCORE = 0; static final public int MAX_SCORE = 100; It’s OK to put static first. Java doesn’t care about the order of visibility modifiers. In model classes, this style is used a lot by programmers to make the class variables, class constants, and class methods stand out. 107

109 10.8 Using Class Constants in a Driver File Here is an example of how the two Student class constants could be used in a driver program: if (test Student.MAX_SCORE) 108

110 10.8 Two Rules about Model Class Methods Two rules you should be aware of when using class variables and class constants: 1. Class methods can reference only class variables and class constants …. but never instance variables. 2. Instance methods can reference either instance variables or class variables and class constants. 109

111 10.8 public static void main ( ) One final note about the Java keyword static. The main method for an executable java class is static. Remember how it is declared: public static void main (String args [ ]) Pretend we have a driver program named MyApp.java When we choose Run As Java Application, the JVM sends the message main to the class MyApp to start the program. It’s a static method call. 110

112 Chapter 10 – Section 9 Enhanced For Loops 111

113 10.9 General Form of an Enhanced For Loop An enhanced for loop (or a for each loop) is an optional easy and simple way to access all of the elements in a list, like an array or an ArrayList, but it won’t let you make changes to the array. The list can contain primitives or object values. Syntax: for ( : ) { } colon NOT semicolon 112

114 10.9 Using an Enhanced For Loop to Print // Printing the elements in a one-dimensional array all on one line with two spaces in between values. double [ ] xyz = { 37.4, 28.9, 43.6, 17.7, 55.5 }; for (double element : xyz ) // element is the Loop Control Variable { System.out.print(element + “ ”); } // compare the above enhanced for loop to this regular for loop for (int i = 0; i < xyz.length; i++) { double element = xyz[i]; System.out.print(element + “ ”); } 113

115 10.9 Using an Enhanced For Loop to Sum // Sum the elements in a one-dimensional array with a for-each loop double [ ] xyz = { 37.4, 28.9, 43.6, 17.7, 55.5 }; double sum = 0; for (double element : xyz ) // element is the Loop Control Var { sum += element; } System.out.println(The sum is: " + sum); 114

116 10.9 Using an Enhanced For Loop to Extract Data in the Elements of an Array // print the number of characters in each name String [ ] names = {“Ann”, “Bill”, “Bob”, “Carol”, “Dan”}; for (String element : names ) // element is the LCV { int numOfChars = element.length(); System.out.print(“The number of characters in ” + element ); System.out.println(“ is ” + numOfChars ); } 115

117 10.9 Using an Enhanced For Loop to Count int [ ] nums = new int [300]; for (int i = 0; i < nums.length; i++) { nums[i] = (int)(Math.random() * 200) + 1; } // Count the number of odd integers in the array int count = 0; for (int element : nums ) // element is the LCV { if (element % 2 == 1) count++; } System.out.println(“The number of odds is: ” + count); 116

118 10.9 Correct Printing of 10 Values Per Line This code appeared earlier in a standard for loop, but now appears in a for each loop. public static void printIntArray(int [ ] array) { int count = 1; for ( int element : array) { if (count % 10 == 0) System.out.printf(“%5d%n”, element); else System.out.printf(“%5d”, element ); count++; } 117

119 10.9 Using an Enhanced For Loop to Search int x = reader.nextInt(); boolean found = false; for ( int element : nums ) { if (element == x) { found = true; break; } if (found) System.out.println(“Found!”); else System.out.println(“NOT Found!”); Assume an array of ints named nums has been declared, instantiated, and filled with values. 118

120 10.9 Using an Enhanced For Loop to Search String str = reader.nextLine(); boolean found = false; for ( String element : names ) { if (element.equals(str)) { found = true; break; } if (found) System.out.println(“Found!”); else System.out.println(“NOT Found!”); 119

121 10.9 When to Use an Enhanced For Loop You can use an enhanced for loop when … no changes need to be made to the elements in the array you will only move through the array in forward order, and you don’t need to move through the array in reverse order you don’t need to know the position of a value in the list you don’t need to access any element other than the current element on each iteration of the loop. (You can access more than one element with a regular for loop if the code is written correctly.) the array is full and there are no invalid portions of the array 120

122 Chapter 10 – Section 10 Arrays of Other Objects 121

123 10.10 Arrays of Objects You have worked with arrays of ints, arrays of doubles, and even arrays of String, but what we want to be able to do is work with arrays of objects other than String. We could work with an array of Student objects, or an array of Teacher objects, or an array of Circle objects, or an array of any kind of object. The only thing we need to be aware of is how to call the methods of the class of object that are in the array! 122

124 10.10 A Teacher Class public class Teacher { private String name; private String subject; public Teacher (String nm, String sbj) { name = nm; subject = sbj; } public String getName ( ) { return name; } public String getSubject ( ) { return subject ; } // other methods not shown } Consider the Teacher class, partially seen here. Assume that a full Teacher model class has been written but not all of the methods are shown. We will only need the methods shown for examples on the next few slides. 123

125 10.10 TeacherDriver Class Code In the main() method of a driver program, we could construct some teachers as follows and add them to an array of Teacher objects. Teacher t1 = new Teacher (“Mr. Smith”, “Math”); Teacher t2 = new Teacher (“Mrs. Jones”, “History”); Teacher t3 = new Teacher (“Ms. Carter”, “Math”); Teacher t4 = new Teacher (“Mr. Carter”, “English”); … all the teachers of a school are constructed and added to an array …. Teacher [ ] teachers = {t1, t2, t3, t4, t5, t6 ………….. }; 124

126 10.10 Code that Finds “Math” Teachers In the main() method, we call the method getMathTeachers to get all of the teachers in the teachers array that are math teachers. Since the method returns an array of Teachers, we must have an array of Teacher objects variable, mathTeachers, to catch the returned array: Teacher [ ] mathTeachers = getMathTeachers (teachers); public static Teacher [ ] getMathTeachers (Teacher [ ] teachers) { // Missing code here that counts the number of math teachers and stores the number in count. // We want our mathTeachers array to be full when we are done copying so we count first! Teacher [ ] mathTeachers = new Teacher [count]; // construct the array to be returned int i = 0; for (Teacher element : teachers ) { if ( element.getSubject().equals(“Math”) ) { * mathTeachers [ i ] = element ; // the teacher in element is added to the new array i++; } return mathTeachers ; // the new array is returned } * Note: You can’t use if( element.equals(“Math”) ) above because element is not a String object. Only a String object can call equals. Element is a Teacher object. 125

127 Chapter 10 - Section 11 Removing and Adding Elements from an Array 126

128 10.11 Removing Elements from an Array Assume the following code: int [ ] nums = new int [8]; int logicalSize = 0; //code that adds 7, 4, 9, 1, & 6 to the array and increments logicalSize up to 5 749 1 6 0 0 0 [0][1][2][3][4][5][6][7] Removing the last valid data element (6) from the end of the array requires us to do one of two things: 1) decrement the logical size by one (from 5 down to 4) 2) replace 6 with the default value that the array is filled with and then decrement the logical size by 1 (from 5 down to 4). 127

129 10.11 Removing Elements from an Array 749 1 6 0 0 0 [0][1][2][3][4][5][6][7] Using the first approach, where we only decrement the logical size by one with no replacement, the program just simply “forgets about 6” because it is in the invalid part of the array. When we do this, 6 is actually still in the array, but if we use the logical size to manipulate the values in the array, we will never access 6 and everything will work fine. The array ends up looking like this with the red values in the invalid part of the array and the logical size is now 4. 128

130 10.11 Removing Elements from an Array Using the second approach, we use these lines of code: nums[logicalSize - 1] = 0; logicalSize--; … we not only replace 6 with 0, the default value for the array, but also decrement the logical size by one. No matter what the size of the array is, the code: nums[logicalSize - 1] = 0; will replace the last value in the valid part of the array. Note: if the logicalSize is 5, the last value is at logicalSize - 1 which is 4. These two lines must be done in this order or it won’t work! 749 1 0 0 0 0 [0][1][2] [3] [4] [5] [6] [7] 129

131 10.11 Removing Elements from an Array What needs to happen to the array when we remove an element in the middle of the portion of the array that has valid values? 130

132 10.11 Removing Elements from an Array Assume the original array we started with that has 5 valid values. To remove 9 in the middle of the portion of the array that is valid, we copy 1 and overwrite 9 with it, now we have 7, 4, 1, 1, 6. Then we copy 6 and overwrite the 1 at index 3 and then decrement the logical size. Complete 749 1 6 0 0 0 [0][1][2][3][4][5][6][7] 741 1 6 0 0 0 [0][1][2][3][4][5][6][7] 741 6 6 0 0 0 [0][1][2][3][4][5][6][7] Intermediate Start 131

133 10.11 Adding Elements in the Middle of the Array Assume the following code: int [ ] nums = new int [8]; int logicalSize = 0; //code that adds 7, 4, 9, 1, & 6 to the array and increments logicalSize up to 5 749 1 6 0 0 0 [0][1][2][3][4][5][6][7] Adding the value 8 at index 3 requires us to shift the data items beginning at index 3 down first and then insert 8 at index 3. Then finally, we will increment the logical size by one (from 5 up to 6). 132

134 10.11 Adding Elements in the Middle of the Array First, we copy 6 and overwrite the 0 at index 5. Second, we copy the 1 at index 3 and overwrite the 6 at index 4. Finally, we replace the 1 at index 3 with 8 and then increment the logical size by 1. Finally 749 1 6 6 0 0 [0][1][2][3][4][5][6][7] 749 1 1 6 0 0 [0][1][2][3][4][5][6][7] 741 8 1 6 0 0 [0][1][2][3][4][5][6][7] Second First 133

135 Chapter 10 - Section 12 UML Diagrams 134

136 10.12 The Model/View/Pattern of Programs Real-life applications contain numerous files organized with the model/view/controller pattern, because most of the time there are many more than just two or three files in a program. The StudentTestScores program is organized into different files that represent the model classes and the view class. This dividing of responsibility within the program promotes code reuse and simplifies what each part of the program does. In this program: – the view class will manage the user interface. – the model classes will manage the student database. 135

137 10.12 StudentTestScores UML Diagram The StudentTestScores program is large enough and complex enough to require a UML diagram to show the relationships between all of the classes in the program. Student class defines a Student object TestScoresModel class defines a Student database of up to 10 Students TestScoresViewApplet class an applet driver program that uses 1 TestScoresModel object 0..10 1 136

138 10.12 What are UML Diagrams? UML diagrams are the industry standard for designing and representing a set of interacting classes. UML stands for Unified Modeling Language. It is a graphical notation developed by software professionals to design and document object- oriented systems. 137

139 10.12 StudentTestScores UML Diagram A solid arrow ending in a diamond indicates that the class nearest the diamond uses an object of the class at the other end of the arrow. Here, TestScoresViewApplet declares and constructs one TestScoresModel object and TestScoresModel declares and constructs from 0 to 10 Student objects. Student class defines a Student object TestScoresModel class defines a Student database of up to 10 Students TestScoresViewApplet class an applet driver program that uses 1 TestScoresModel object 0..10 1 138

140 10.12 StudentTestScores UML Diagram The numbers that label these arrows show the number of instances of the class that are used. These numbers can be a fixed number (like 1) or a range (like 0..10) or a star *, which means zero or more. Student class defines a Student object TestScoresModel class defines a Student database of up to 10 Students TestScoresViewApplet class an applet driver program that uses 1 TestScoresModel object 0..10 1 139

141 10.12 StudentTestScores GUI Applet Program Here is the organization of the GUI Applet version of the StudentTestScores program: First Model class - Student class that models a Student object Second Model class - TestScoresModel that models the database of Student objects (an array of Student objects) View class - TestScoresViewApplet is the GUI driver that provides the view for the applet version of the program. Controller classes - private inner classes in the TestScoresViewApplet driver file. 140

142 10.12 The StudentTestScores Applet Code Let’s look at the code for the files of the program … Student TestScoresModel TestScoresViewApplet and run it. 141


Download ppt "Chapter 10 The One-Dimensional Array Section 1 - What is a One-Dimensional Array? Section 2 - Declaring and Instantiating an Array Section 3 - The Power."

Similar presentations


Ads by Google