1 / 83

Chapter 9: Arrays

Chapter 9: Arrays. J ava P rogramming: From Problem Analysis to Program Design, Second Edition. Chapter Objectives. Learn about arrays. Explore how to declare and manipulate data into arrays. Understand the meaning of “array index out of bounds.”

may
Télécharger la présentation

Chapter 9: Arrays

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 9: Arrays JavaProgramming: From Problem Analysis to Program Design, Second Edition

  2. Chapter Objectives • Learn about arrays. • Explore how to declare and manipulate data into arrays. • Understand the meaning of “array index out of bounds.” • Become familiar with the restrictions on array processing. Java Programming: From Problem Analysis to Program Design, Second Edition

  3. Chapter Objectives • Discover how to pass an array as a parameter to a method. • Discover how to manipulate data in a two-dimensional array. • Learn about multidimensional arrays. Java Programming: From Problem Analysis to Program Design, Second Edition

  4. Array • Is a collection of a fixed number of components, where all the components are of the same data type. • Components are accessed using their relative positions in the array. Java Programming: From Problem Analysis to Program Design, Second Edition

  5. One-Dimensional Arrays • Syntax to instantiate an array: • dataType[ ] arrayName; arrayName = new dataType[intExp] • dataType[ ] arrayName = new dataType[intExp] • dataType[ ] arrayName1, arrayName2; Java Programming: From Problem Analysis to Program Design, Second Edition

  6. Array num int[] num = newint[5]; Java Programming: From Problem Analysis to Program Design, Second Edition

  7. Alternate Ways to Declare an Array int[] num ; int num[]; int[] list; int list[]; Java Programming: From Problem Analysis to Program Design, Second Edition

  8. Alternate ways to declare an array int alpha[] , beta; //line2 Int[] gamma , delta; //line3 Java Programming: From Problem Analysis to Program Design, Second Edition

  9. One-Dimensional Arrays • Syntax to access an array component: • arrayName[indexExp] • intExp = number of components in array >= 0 • 0 <= indexExp < intExp Java Programming: From Problem Analysis to Program Design, Second Edition

  10. Accessing Array Components int[] list = new int [10]; list[5] = 34; or i = 5; list[i] = 34; or i = 4; list[2 * i – 3] = 34; Java Programming: From Problem Analysis to Program Design, Second Edition

  11. Array list Java Programming: From Problem Analysis to Program Design, Second Edition

  12. Array Declaration • final int ARRAY_SIZE = 10; • int[] list = newint[ARRAY_SIZE]; Java Programming: From Problem Analysis to Program Design, Second Edition

  13. Specifying Array Size During Program Execution int arraySize; System.out.print("Enter the size of " + "the array: "); arraySize = console.nextInt(); System.out.println(); int[] list = newint[arraySize]; Dynamic arrays Java Programming: From Problem Analysis to Program Design, Second Edition

  14. Array Initialization During Declaration double[] sales = {12.25, 32.50, 16.90, 23, 45.68}; • The values, called initial values, are placed between braces and separated by commas. • Here, sales[0]= 12.25, sales[1]= 32.50, sales[2]= 16.90, sales[3]= 23.00, and sales[4]= 45.68. • When declaring and initializing arrays, the size of the array is determined by the number of initial values within the braces. • If an array is declared and initialized simultaneously, we do not use the operator new to instantiate the array object. Java Programming: From Problem Analysis to Program Design, Second Edition

  15. Arrays and the Instance Variable length • A public instance variable length is associated with each array that has been instantiated. • The variable length contains the size of the array. • The variable length can be directly accessed in a program using the array name and the dot operator. • Consider the following declaration: int[] list = {10, 20, 30, 40, 50, 60}; • This statement creates the array list of six components and initializes the components using the values given. Here list.length is 6. Java Programming: From Problem Analysis to Program Design, Second Edition

  16. Arrays and the Instance Variable length • This statement creates the array numList of 10 components and initializes each component to 0. int[] numList = new int[10]; • The value of numList.length is 10. • These statements store 5, 10, 15, and 20, respectively, in the first four components of numList. numList[0] = 5; numList[1] = 10; numList[2] = 15; numList[3] = 20; • You can store the number of filled elements, that is, the actual number of elements, in the array in a variable, say noOfElement. It is a common practice for a program to keep track of the number of filled elements in an array. Java Programming: From Problem Analysis to Program Design, Second Edition

  17. Processing One-Dimensional Arrays • Loops used to step through elements in array and perform operations. int[] list = new int[100]; int i; for (i = 0; i < list.length; i++) //process list[i], the (i + 1)th //element of list for (i = 0; i < list.length; i++) list[i] = console.nextInt(); for (i = 0; i < list.length; i++) System.out.print(list[i] + " "); Java Programming: From Problem Analysis to Program Design, Second Edition

  18. Arrays • Some operations on arrays: • Initialize • Input data • Output stored data • Find largest/smallest/sum/average of elements double[] sales = newdouble[10]; int index; double largestSale, sum, average; Java Programming: From Problem Analysis to Program Design, Second Edition

  19. Code to Initialize Array to Specific Value (10.00) for (index = 0; index < sales.length; index++) sales[index] = 10.00; Java Programming: From Problem Analysis to Program Design, Second Edition

  20. Code to Read Data into Array for (index = 0; index < sales.length; index++) sales[index] = console.nextDouble(); Java Programming: From Problem Analysis to Program Design, Second Edition

  21. Code to Print Array for (index = 0; index < sales.length; index++) System.out.print(sales[index] + " "); Java Programming: From Problem Analysis to Program Design, Second Edition

  22. Code to Find Sum and Average of Array sum = 0; for (index = 0; index < sales.length; index++) sum = sum + sales[index]; if (sales.length != 0) average = sum / sales.length; else average = 0.0; Java Programming: From Problem Analysis to Program Design, Second Edition

  23. Determining Largest Element in Array maxIndex = 0; for (index = 1; index < sales.length; index++) if (sales[maxIndex] < sales[index]) maxIndex = index; largestSale = sales[maxIndex]; Java Programming: From Problem Analysis to Program Design, Second Edition

  24. Determining Largest Element in Array Java Programming: From Problem Analysis to Program Design, Second Edition

  25. Example 9-4 Java Programming: From Problem Analysis to Program Design, Second Edition

  26. Array Index Out of Bounds • An array is in bounds if: 0 <= index <= arraySize – 1 • If index < 0 or index > arraySize: In Java, if an array index goes out of bounds during program execution, it throws an ArrayIndexOutOfBoundsException exception. If the program does not handle this exception, the program terminates with an appropriate error message. Java Programming: From Problem Analysis to Program Design, Second Edition

  27. Declaring Arrays as Formal Parameters to Methods General syntax to declare an array as a formal parameter: dataType[] arrayName public static void arraysAsFormalParameter(int[] listA, double[] listB, int num) { //... } int[] intList = newint[10]; double[] doubleNumList = newdouble[15]; int number; arraysAsFormalParameter(intList, doubleNumList, number); Java Programming: From Problem Analysis to Program Design, Second Edition

  28. The Assignment Operators and Arrays int[] listA = {5, 10, 15, 20, 25, 30, 35}; int[] listB= new int[listA.length]; Java Programming: From Problem Analysis to Program Design, Second Edition

  29. The Assignment Operators and Arrays Java Programming: From Problem Analysis to Program Design, Second Edition

  30. The Assignment Operators and Arrays listB = listA; Java Programming: From Problem Analysis to Program Design, Second Edition

  31. The Assignment Operators and Arrays Java Programming: From Problem Analysis to Program Design, Second Edition

  32. The Assignment Operators and Arrays Shallow copying of data Java Programming: From Problem Analysis to Program Design, Second Edition

  33. The Assignment Operators and Arrays for (int index = 0; index < listA.length; index++) listB[index] = listA[index]; Java Programming: From Problem Analysis to Program Design, Second Edition

  34. The Assignment Operators and Arrays deep copying of data Java Programming: From Problem Analysis to Program Design, Second Edition

  35. Relational Operators Arrays • if (listA == listB) • ... • The expression listA == listB determines if the values of listA and listB are the same, thus determining whether listA and listB refer to the same array. • To determine whether listA and listB contain the same elements, you need to compare them component by component. • You can write a method that returns true if two int arrays contain the same elements. Java Programming: From Problem Analysis to Program Design, Second Edition

  36. Relational Operators and Arrays boolean isEqualArrays(int[] firstArray, int[] secondArray) { if (firstArray.length != secondArray.length) return false; for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) return false; return true; } if (isEqualArrays(listA, listB)) ... Java Programming: From Problem Analysis to Program Design, Second Edition

  37. Methods for Array Processing To write methods to process arrays, in addition to declaring an array as a formal parameter, we declare another formal parameter specifying the number of elements in the array. Java Programming: From Problem Analysis to Program Design, Second Edition

  38. Methods for Array Processing public static void fillArray(int[] list, int noOfElements) { int index; for (index = 0; index < noOfElements; index++) list[index] = console.nextInt(); } Java Programming: From Problem Analysis to Program Design, Second Edition

  39. Methods for Array Processing public static void fillArray(int[] list, int noOfElements) { int index; for (index = 0; index < noOfElements; index++) list[index] = console.nextInt(); } Java Programming: From Problem Analysis to Program Design, Second Edition

  40. Methods for Array Processing public static void printArray(int[] list, int noOfElements) { int index; for (index = 0; index < noOfElements; index++) System.out.print(list[index] + " "); } public static int sumArray(int[] list, int noOfElements) { int index; int sum = 0; for (index = 0; index < noOfElements; index++) sum = sum + list[index]; return sum; } Java Programming: From Problem Analysis to Program Design, Second Edition

  41. Methods for Array Processing public static int indexLargestElement(int[] list, int noOfElements) { int index; int maxIndex = 0; for (index = 1; index < noOfElements; index++) if (list[maxIndex] < list[index]) maxIndex = index; return maxIndex; } public static void copyArray(int[] list1, int[] list2, int noOfElements) { int index; for (index = 0; index < noOfElements; index++) list2[index] = list1[index]; } Java Programming: From Problem Analysis to Program Design, Second Edition

  42. Base Address of an Array • The base address of an array is the address (memory location) of the first array component. • The base address of list is the address of list[0] Java Programming: From Problem Analysis to Program Design, Second Edition

  43. Parallel Arrays • Arrays are parallel if the corresponding components hold related information. Java Programming: From Problem Analysis to Program Design, Second Edition

  44. Parallel Arrays int[] studentId = new int[50]; char[] courseGrade = new char[50]; Int noOfStudents = 0; While (infile.hasNext() && noOfStudent < 50) { studentId[noOfStudents] = infile.nextInt(); courseGrade[noOfStudents] = infile.next().charAt(0); noOfStudents++; } Java Programming: From Problem Analysis to Program Design, Second Edition

  45. Arrays of Objects • Can use arrays to manipulate objects. • Example: Create an array named array1 with N objects of type T: T[] array1 = new T[N] • Can instantiate array1 as follows: for(int j=0; j <array1.length;j++) array1[j] = new T(); Java Programming: From Problem Analysis to Program Design, Second Edition

  46. Array of String Objects String[] nameList = new String[5]; nameList[0] = "Amanda Green"; nameList[1] = "Vijay Arora"; nameList[2] = "Sheila Mann"; nameList[3] = "Rohit Sharma"; nameList[4] = "Mandy Johnson"; Java Programming: From Problem Analysis to Program Design, Second Edition

  47. Array of String Objects Java Programming: From Problem Analysis to Program Design, Second Edition

  48. Array of String Objects To output the names!! Java Programming: From Problem Analysis to Program Design, Second Edition

  49. Array of String Objects You can use String methods to work with the objects of nameList. For example, the expression: nameList[0].equals("Amanda Green") evaluates to true. Java Programming: From Problem Analysis to Program Design, Second Edition

  50. Arrays of Objects Clock[] arrivalTimeEmp =newClock[100]; Java Programming: From Problem Analysis to Program Design, Second Edition

More Related