Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 Arrays and the ArrayList Class Introduction to Arrays.

Similar presentations


Presentation on theme: "Chapter 8 Arrays and the ArrayList Class Introduction to Arrays."— Presentation transcript:

1 Chapter 8 Arrays and the ArrayList Class Introduction to Arrays

2 2 Contents I. What is an Array? II. Processing Array Elements III. Passing Arrays As Arguments to Methods IV. Some Useful Array Algorithms and Operations V. Returning Arrays from Methods VI. The Sequential Search Algorithm

3 3 I. What is an Array? 1. One-Dimensional Arrays 2. Accessing Array Elements 3. Inputting and Outputting Array Contents 4. Java Performs Bounds Checking 5. Watch Out for Off-by-One Errors 6. Array Initialization 7. Alternate Array Declaration Notation

4 4 I.1. One-Dimensional Arrays An one-dimensional array (array) is an object that can store a group of value, all of the same type. Declaration of an array reference variable numbers. int[] numbers; The numbers variable can reference an array of int values. Creating an array of 10 int values: number = new int[10]; Size of array

5 5 I.1. One-Dimensional Arrays int count; double number; char letter; int[] numbers = new int[5]; 1234 Enough memory to hold one int 1234.55 Enough memory to hold one double A Enough memory to hold one char 0 numbers variable Ele men t 0 0 Ele men t 1 0 Ele men t 2 0 Ele men t 3 0 Ele men t 4

6 6 I.1. One-Dimensional Arrays Examples: int[] numbers = new int[5]; float[] temperatures = new float[100]; char[] letters = new char[41]; long[] units = new long[50]; double[] sizes = new double[1200]; final int NUM_ELEMENTS = 5; int[] numbers = new int[NUM_ELEMENTS]; Once an array is created, its size cannot be changed. By default, Java initializes array elements with 0.

7 7 I.2. Accessing Array Elements Each element in an array is assigned a number known as a subscript. A subscript is used as an index to point a specific element within an array. The first element is assigned the subscript 0, the second element is assigned 1, and so forth. Each element in an array can be used as a variable. int[] numbers = new int[5]; 0 numbers variable 0 0 1 0 2 0 3 0 4 subscript

8 8 I.2. Accessing Array Elements Each element in the array is accessed by its subscript. int[] numbers = new int[5]; numbers[0] = 20; numbers[1] = 25; numbers[2] = 30; numbers[3] = 35; numbers[4] = 40; 20 numbers variable numb ers[ 0] 25 numb ers[ 1] 30 numb ers[ 2] 35 numb ers[ 3] 40 numb ers[ 4]

9 9 I.3. Inputting and Outputting Array Contents

10 10 I.3. Inputting and Outputting Array Contents

11 11 I.4. Java Performs Bounds Checking Java performs array bounds checking. It does not allow a statement to use a subscript that is outside the range of valid subscripts for an array. int[] values = new int[10]; Java will not allow a statement to use a subscript that is less than 0 or greater than 9 with this array. Java will display a runtime error message if a statement that uses an invalid subscript executes.

12 12 I.5. Watch Out for Off-by-One Errors Because array subscript start at 0 rather than 1, you have to careful not to perform an off-by-one error. //This code has an off-by-one error. int[] numbers = new int[100]; for(int index = 1; index <= 100; index++) numbers[index] = 99; The first element, which is at subscript 0, is skipped. The program will crash because 100 is an invalid subscript.

13 13 I.6. Array Initialization Java allows us to initialize an array's elements when we create the array. int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; Java automatically creates the array and stores the values in the initialization list in it. Java determines the size of the array by the number of items in the initialization list. The values are stored in the array elements in the order they appear in the list. The first value, 31, is stored in days[0], the second value, 28, is stored in days[1], and so forth.

14 14 I.7. Alternate Array Declaration Notation Java allows us to use two different styles when declaring array reference variables. int[] numbers; int numbers[]; The difference between the two styles is notices when more than one variable is declared in the same statement. int[] numbers, codes, scores; int numbers[], codes, scores;

15 15 Checkpoint 8.1 Write a statements that create the following arrays” a. A 100-element int array referenced by the variable employeeNumbers. b. A 25-element double array referenced by the variable payRates. c. A 14-element float array referenced by the variable miles.

16 16 Checkpoint 8.2 What's wrong with the following array declarations? int[] readings = new int[-1]; double[] measurements = new double[4.5]; 8.3 What would the valid subscript values be in a four-element array of doubles ? 8.4 What is the difference between an array's size declarator and a subscript? 8.5 What does it mean for a subscript to be out- of-bounds?

17 17 Checkpoint 8.6 What happens in Java when a program tries to use a subscript that is out-of-bounds? 8.7 What is the output of the following code? int[] values = new int[5]; for(int count = 0; count < 5; count++) values[count] = count + 1; for(int count = 0; count < 5; count++) System.out.println(values[count]); 8.8 Write a statement that creates and initializes a double array with the following values: 1.7, 6.4, 8.9, 3.1, and 9.2. How many elements are in the array?

18 18 II. Processing Array Elements 1. Processing Array Elements 2. Array Length 3. The Enhanced for Loop 4. Letting the User Specify an Array's Size 5. Reassigning Array Reference Variables 6. Copying Arrays

19 19 II.1. Processing Array Elements Processing array elements is no different from processing other variables. grossPay = hours[3] * payRate; int[] score = {7, 8, 9, 10, 11}; ++score[2]; score[4]++; amount[count--];

20 20 II.2. Array Length Each array in Java has a public field named length. This field contains the number of elements in the array. double[] temperatures = new double[25];... for(int i = 0; i < temperatures.length; i++) System.out.println(temperatures[i]); The largest subscript in an array is length-1.

21 21 II.3. The Enhanced for Loop Java provides a specialized version of the for loop that, in many circumstances, simplifies array processing. for(dataType elementVariable : array) statement; For example: int[] numbers = { 3, 6, 9 }; for(int val : numbers) System.out.println(val);

22 22 II.3. The Enhanced for Loop When you need to access the values that are stored in an array, from the first element to the last element, the enhanced for loop is simpler to use than the traditional for loop. We cannot use the enhanced for loop as follows: If we need to change the contents of an array element If we need to work through the array elements in reverse order If we need to access some of the array elements, but not all of them

23 23 II.3. The Enhanced for Loop If we need to simultaneously work with two or more arrays within the loop If we need to refer to the subscript number of a particular element

24 24 II.4. Letting the User Specify an Array's Size Java allows us to use an integer variable to specify an array's size declarator. This makes it possible to allow the user to specify an array's size.

25 25

26 26 II.5. Reassigning Array Reference Variables It is possible to reassign an array reference variable to a different array. //Create an array referenced by the numbers variable. int[] numbers = new int[10]; //Reassign numbers to a new array. numbers = new int[5]; address The numbers variables holds the address of an int array The ten-element int array previously referenced A five-element int array

27 27 II.6. Copying Arrays An array is an object. An array and a reference variable are two separate entities. int[] array1 = { 2, 4, 6, 8, 10}; int[] array2 = array1; This does not copy array1. Both array1 and array2 reference the same array. 246810 An int array addres s The array1 variable holds the address of an int array. addres s The array2 variable holds the address of an int array.

28 28 II.6. Copying Arrays To copy an array we need to copy the individual elements of one array to another. Usually, this is best done with a loop, such as the following: int[] firstArray = { 5, 10, 15, 20, 25 }; int[] secondArray = new int[5]; for(int index = 0; index < firstArray.length; index ++) secondArray[index] = firstArray[index];

29 29 Checkpoint 8.9 Look at the following statements: int[] numbers1 = { 1, 3, 6, 9}; int[] numbers2 = { 2, 4, 6, 8}; Write a statement that multiplies element 0 of the numbers1 array by element 3 of the numbers2 array and assigns the result to the result variable. 8.10 A program uses a variable named array that references an array of integers. We do not know the number of elements in the array. Write a for loop that stores -1 in each element of the array.

30 30 Checkpoint 8.11 A program has the following declaration: double[] values; Write code that asks the user for the size of the array and then creates an array of the specified size, referenced by the values variables. 8.12 Look at the following statememts: int[] a = {1, 2, 3, 4, 5, 6, 7}; int[] b = new int[7]; Write code that copies the a array to the b array.

31 31 III. Passing Arrays As Arguments to Methods To pass an array, we pass the value in the variable that references the array. It is passed just as an object is passed: The actual array itself is not passed, but the reference to the array is passed into the parameter. This means the method has direct access to the original array.

32 32 III. Passing Arrays As Arguments to Methods showArray(numbers); public static void showArray(int[] array) { for(int i = 0; i < array.length; i++) System.out.print(array[i] + “ “); } 51015202530 An array address

33 33

34 34

35 35 IV. Some Useful Array Algorithms and Operations 1. Comparing Arrays 2. Summing the Values in a Numeric Array 3. Getting the Average of the Values in a Numeric Array 4. Finding the Highest and Lowest Values in a Numeric Array 5. Partially Filled Arrays 6. Working with Arrays and Files

36 36 IV.1. Comparing Arrays To compare the contents of two arrays, we must compare the elements of the two arrays. We cannot use the == operator to compare two array reference variables and determine the arrays are equal. int[] firstArray = { 5, 10, 15 }; int[] secondArray = { 5, 10, 15}; if(firstArray == secondArray) //This is a mistake. System.out.println(“The arrays are the same.”); else System.out.println(“The arrays are not the same.”);

37 37 IV.1. Comparing Arrays Comparing the contents of two arrays: int[] firstArray = { 5, 10, 15 }; int[] secondArray = { 5, 10, 15}; boolean arrayEqual = true; //Flag variable int index = 0; //Loop control variable //First determine whether the arrays are the same size. if(firstArray.length == secondArray.length) arrayEqual = false; while(arrayEqual && index < firstArray.length) { if(firstArray[index] != secondArray[index]) arrayEqual = false; else index++; } if(arrayEqual) System.out.println(“The arrays are equal.”); else System.out.println(“The arrays are not equal.”);

38 38 IV.2. Summing the Values in a Numeric Array To sum the values in an array we must use a loop with an accumulator variable. The loop adds the value in each array element to the accumulator. int[] units = new int[5]; //.... int acc = 0; // Initialize accumulator for(int index = 0; index < units.length; index++) acc += units[index];

39 39 IV.3. Getting the Average of the Values in a Numeric Array The first step in calculating the average of all the values in an array is to sum the values. The second step is to divide the sum by the number of elements in the array. double[] scores = new double[10]; //.... double acc = 0; // Initialize accumulator double average; //Will hold the average for(int index = 0; index < scores.length; index++) acc += scores[index]; average = acc / scores.length;

40 40 IV.4. Finding the Highest and Lowest Values in a Numeric Array int[] numbers = new int[50]; //.... //Find the highest value int highest = numbers[0]; for(int index = 1; index highest) highest = numbers[index]; } How to find the lowest value ?

41 41 IV.5. Partially Filled Arrays Sometimes we need to store a series of items in an array, but we do not know the number of items that there are. One solution is to make the array large enough to hold the largest possible number of items. If the actual number of items stored in the array is less than the number of elements, the array will be only partially filled. When we process a partially filled array, we must only process the elements that contain valid data items. A partially filled array is normally used with an accompanying integer variable that holds the number of items stored in the array.

42 42 IV.6. Working with Arrays and Files Saving the contents of an array to a file is a straightforward procedure: Use a loop to step through each element of the array, writing its contents to the file. int[] numbers = { 10, 20, 30}; //Open the file FileWriter fwriter = new FileWriter(“Values.txt”); PrintWriter outputFile = new PrintWriter(fwriter); //Write the array elements to the file for(int index=0; index<numbers.length;index++) outputFile.println(numbers[index]); //Close the file outputFile.close();

43 43 IV.6. Working with Arrays and Files Open the file Values.txt and read its contents back into the numbers array: int[] number = new int[5]; String str;// To hold lines read from the file int index = 0; // Loop control variable //Open the file FileReader freader = new FileReader(“Values.txt”); BufferedReader inputFile = new BufferedReader(freader);

44 44 IV.6. Working with Arrays and Files //Read the file contents into the array str = inputFile.readLine(); while(str != null && index < numbers.length) { numbers[index] = Integer.parseInt(str); index++; str = inputFile.readLine(); } //Close the file inputFile.close();

45 45 V. Returning Arrays from Methods A method can return a reference to an array. The return type must be an array reference. public static double[] getArray() { double[] array = {1.2, 2.3, 4.5 }; return array; } Array reference

46 46 VI. The Sequential Search Algorithm A search algorithm is a method of locating a specific item in a large collection of data. The sequential search algorithm uses a loop to sequentially steps through an array: Starts with the first element. Compares each element with the value being searched for. Stops when the value is found or the end of the array is encountered. If the value being searched for is not in the array, the algorithm searched to the end of the array.

47 47

48 48


Download ppt "Chapter 8 Arrays and the ArrayList Class Introduction to Arrays."

Similar presentations


Ads by Google