1 / 141

Chapter 10 The One-Dimensional Array

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

Télécharger la présentation

Chapter 10 The One-Dimensional Array

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 10The 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 Go Go Go Go Go Go Go Go Go Go Go 1

  2. Chapter 10 - Section 1What is aOne-Dimensional Array? 2

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

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

  5. 10.1 Visualizing a One-Dimensional Array • Java provides a data structure called an array.Arrays are acontiguousblock of memory locationsthat can be referred to with one variablelike nums. Here is an array that holds random integers. nums [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. 5

  6. 10.1 What is an Array? An array is acollectionof 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

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

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

  9. 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 primitive types reference types 9

  10. Here is how a number of different arrays of different types can be visualized: 10.1 Example Arrays tests names temps students 10

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

  12. Chapter 10 - Section 2Declaring and Instantiating Arrays 12

  13. 10.2 Standard Array Construction physical size in the [ ] 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. 13

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

  15. 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. nums 15

  16. 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.0since the array will contain primitive double values. temps 16

  17. 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 names 17

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

  19. 10.2 The Physical Size of an Array A standard array has a public variableor 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

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

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

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

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

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

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

  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] = 23 a[a.length-1] = 12 a[2] + a[3] = 67 + 89 = 156 26

  27. Chapter 10 - Section 3The Power of Using Loopswith Arrays 27

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

  29. 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 codegenericso 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

  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(); 10.3 Assignment Statements Used to Store values to be stored on the right side. array memory locations designated on the left side 30

  31. 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. It is important to initialize i to zero not 1, because the first element of an array is at index zero! 31

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

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

  34. 10.3 Printing Values in an Array with Printf To usea count upfor loop that will print all of the random integers in numsone per lineright 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

  35. 10.3 Printing Values in an Array with Printf To usea count upfor loop that will print all of the random integers in numson one lineright 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

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

  37. 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 lineright 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

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

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

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

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

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

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

  44. 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 holdsprimitives count++; } System.out.println( x + “ occurs ” + count + “ times!”); 44

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

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

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

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

  49. Chapter 10 - Section 4Array Physical and Logical SizesAdding Values to an ArrayRemoving Values from an Array 49

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

More Related