1 / 51

Arrays

Chapter 6. Arrays. Announcements. Project 3 is done! Project 4 is out! (Due in one week) We have reached the point where you must start on time to finish projects Cancelled labs will be made available Grades will be prorated Should do them on your own. Exam: Programming Q. 1.

andie
Télécharger la présentation

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 6 Arrays Chapter 6

  2. Chapter 6 Announcements • Project 3 is done! • Project 4 is out! (Due in one week) • We have reached the point where you must start on time to finish projects • Cancelled labs will be made available • Grades will be prorated • Should do them on your own

  3. Chapter 6 Exam: Programming Q. 1 public int dayOfYear() { int count =0; for(int i =1; i <= month -1; i++){ count += numDays( i ); } count += day; return count; } public int compareTo( Date other ) { if( month == other.getMonth()){ return day - other.getDay(); }else{ return month - other.getMonth(); } }

  4. Chapter 6 Exam: Programming Q. 2 import java.util.Scanner; publicclass Padovan { publicstaticvoid main(String[] args) { Scanner s =new Scanner(System.in); System.out.print("k: "); int k = s.nextInt(); int p0 =1, p1 =1, p2 =2; if(k <1)return; System.out.print(p0 +" "+ p1 +" "+ p2); int pnew = p0 + p1; while(pnew <= k) { System.out.print(" "+ pnew); p0 = p1; p1 = p2; p2 = pnew; pnew = p0 + p1; } } }

  5. Chapter 6 Exam: Programming Q. 3 publicclass Tokenizer{ publicstaticfinalchar DELIMITER =','; publicstaticvoid main(String args[]){ Tokenizer t =new Tokenizer(); Scanner keyboard =new Scanner(System.in); System.out.println("Enter a string:"); String input = keyboard.nextLine(); t.tokenize(input); } publicvoid tokenize(String input){ System.out.println("Tokens:"); for(int i =0; i < input.length(); i++){ if(input.charAt(i)== DELIMITER){ System.out.println(); } else{ System.out.print(input.charAt(i)); } } } }

  6. Chapter 6 Creating and Accessing Arrays • example double[] temperature = new double[7]; is like declaring seven variables of type double, named temperature[0], temperature[1], temperature[2], temperature[3], temperature[4], temperature[5], temperature[6].

  7. Chapter 6 Creating and Accessing Arrays, cont. • These variables can be used just like any other variables of type double. • examples temperature[3] = 32.0; temperature[6] = temperature[3] + 5; System.out.println(temperature[6]); temperature[index] = 66.5; • These variables are called indexed variables, elements, or subscripted variables.

  8. Chapter 6 The length Instance Variable • An array has only one public instance variable, length. • The length variable stores the number of elements the array can hold. • Using Array_Name.length typically produces clearer code than using an integer literal.

  9. Chapter 6 The length Instance Variable, cont • class ArrayOfTemperatures2

  10. Chapter 6 Indices and length • The indices of an array start with 0 and end with Array_Name.length-1. • When a for loop is used to step through an array, the loop control variable should start at 0 and end at length-1. • example for (lcv = 0; lcv < temperature.length; lcv++)

  11. Chapter 6 Initializing Arrays • An array can be initialized at the time it is declared. • example double[] reading = {3, 3, 15.8, 9.7}; • The size of the array is determined by the number of values in the initializer list.

  12. Chapter 6 Initializing Arrays, cont. • Uninitialized array elements are set to the default value of the base type. • However, it’s better to use either an initializer list or a for loop. int[] count = new int[100]; for (int i = 0, i < count.length, i++) { count[i] = 0; }

  13. Chapter 6 Case Study: Using an Array as an Instance Variable, cont. • class SalesReporter

  14. Chapter 6 Indexed Variables as Method Arguments • An indexed variable can be used anywhere that any other variable of the base type of the array can be used. • Hence, an indexed variable can be an argument to a method.

  15. Chapter 6 Indexed Variables as Method Arguments, cont. • class ArgumentDemo

  16. Chapter 6 Entire Arrays as Method Arguments • An entire array can be used as a single argument passed to a method. • example double[] a = new double[10]; SampleClass.change(a); ... public static void change(double[] d) • No brackets accompany the argument. • Method change accepts an array of any size.

  17. Chapter 6 Arguments for the Method main • Recall the heading for method main: public static void main(String[] args) • Method main takes an array of String values as its argument.

  18. Chapter 6 Arguments for the Method main, cont. • An array of String values can be provided in the command line. • example java TestProgram Mary Lou • args[0]is set to“Mary” • args[1]is set to“Lou” System.out.println(“Hello “ + args[0] + “ “ + args[1]); printsHello Mary Lou.

  19. Chapter 6 Use of = and == with Arrays • The assignment operator = and the equality operator ==, when used with arrays, behave the same as when used with other objects. • The assignment operator creates an alias, not a copy of the array. • The equality operator determines if two references contain the same memory address, not if two arrays contain the same values.

  20. Chapter 6 Making a Copy of an Array • example int[] a = new int[50]; int[] b = new int[50]; ... for (int j = 0; j < a.length; j++) b[j] = a[j];

  21. Chapter 6 Determining the “Equality” of Two Arrays • To determine if two arrays at different memory locations contain the same elements in the same order, define an equals method which determines if • both arrays have the same number of elements • each element in the first array is the same as the corresponding element in the second array.

  22. Chapter 6 Determining the “Equality” of Two Arrays, cont. • A while loop can be used. • A boolean variable match is set to true. • Each element in the first array is compared to the corresponding element in the second array. • If two elements are different, match is set to false and the while loop is exited. • Otherwise, the loop terminates with match still set to true.

  23. Chapter 6 Determining the “Equality” of Two Arrays, cont. • class TestEquals

  24. Chapter 6 Determining the “Equality” of Two Arrays, cont. • Common functionality is built in: • java.util.Arrays.equals( [], [] )

  25. Chapter 6 Methods that Return Arrays • A method can return an array. • The mechanism is basically the same as for any other returned type. • example public static Base_Type[] Method_Name (Parameter_List) Base_Type Array_Name; … return Array_Name; • The method need not be public or static.

  26. Chapter 6 Methods that Return Arrays, cont. • class ReturnArrayDemo

  27. Chapter 6 Partially Filled Arrays • Sometimes you need some, but not all of the indexed variables in an array. • In such situations, it is important to keep track of how much of the array has been used and/or the index of the last entry so that only meaningful values are accessed.

  28. Chapter 6 Partially Filled Arrays, cont.

  29. Chapter 6 Sorting Arrays • Sometime we want numbers in an array sorted from smallest to largest, or from largest to smallest. • Sometimes we want the strings referenced by an array to be in alphabetical order. • Sorting techniques typically are easy to adapt to sort any type that can be ordered.

  30. Chapter 6 Selection Sort • The selection sort arranges the values in an an array so that a[0] <= a[1] <= a[2] … <= a[a.length-1] • The selection sort places the smallest item in a[0], the next smallest item in a[1], and so on for all but the last item. for(i = 0; i <a.length-1; i++) place the ith smallest item in a[i]

  31. Chapter 6 Selection Sort, cont. • Selection sort begins by finding the smallest item in the array and swapping it with the item in a[0]. • Selection sort continues by finding the smallest item in the remainder of the array and swapping it with the next item in array a. • Selection sort terminates when only one item remains.

  32. Chapter 6 Selection Sort, cont.

  33. Chapter 6 Selection Sort, cont. • class SelectionSort

  34. Chapter 6 Swapping Elements • To swap two elements a[i] and a[j], one of them must be saved temporarily.

  35. Chapter 6 Swapping Elements, cont. • class interchange

  36. Chapter 6 Introduction to Multidimensional Arrays • An array with more than one index sometimes is useful. • example: savings account balances at various interest rates for various numbers of years • columns for interest rates • rows for years • This two-dimensional table calls for a two-dimensional array.

  37. Chapter 6 Introduction to Multidimensional Arrays, cont.

  38. Chapter 6 Introduction to Multidimensional Arrays, cont.

  39. Chapter 6 Introduction to Multidimensional Arrays, cont. • An array with n indices is called an n-dimensional array. • The arrays we considered previously, which had one index, were one-dimensional arrays.

  40. Chapter 6 Multidimensional-Array Basics • example declaration int[][] table = new int [10][6]; or int[][] table; table = new int[10][6]; • The number of bracket pairs in the declaration is the same as the number of indices.

  41. Chapter 6 Multidimensional-Array Basics, cont. • syntax Base_Type[]…[] Array_Name = new Base_Type[Length_1]…[Length_n]; • examples char[][] page = new char [100][80]; double[][][] threeDPicture = new double[10][20][30]; SomeClass[][] entry = new SomeClass[100][80];

  42. Chapter 6 Multidimensional-Array Basics, cont. • Nested for loops can be used to change the values of the elements of the array and to display the values of the elements of the array.

  43. Chapter 6 Multidimensional-Array Basics, cont. • class InterestTable

  44. Chapter 6 Multidimensional-Array Parameters • Methods may have multidimensional-array parameters.

  45. Chapter 6 Multidimensional-Array Parameters, cont. • class InterestTable2

  46. Chapter 6 Multidimensional-Array Returned Values • A method may return a multidimensional array. • example public static double[][] corner(double[][] sArray, int i) { double[][] temp = new double[i][i]; … return temp; }

  47. Chapter 6 Implementation of Multidimensional Arrays • Multidimensional arrays are implemented in Java using one-dimensional arrays. • Consider int[][] table = new int[10][6]; • The array table is a one-dimensional array of length 10. • Its base type is int[]. • Therefore, it is an array of arrays.

  48. Chapter 6 Implementation of Multidimensional Arrays, cont. • This permits us to use the length instance variable, instead of an integer literal, to control a for loop used to initialize or print the values of the elements of an array. • example for (r = 0; r < table.length; r++) for (c = 0; c < table[r].length; c++)

  49. Chapter 6 Implementation of Multidimensional Arrays, cont. • redefinedmethod showTable

  50. Chapter 6 Ragged Arrays • Since a two-dimensional array in Java is an array of arrays, each row can have a different number of elements (columns). • Arrays in which rows have different numbers of elements are called ragged arrays.

More Related