1 / 87

Chapter 7

Chapter 7. Arrays…. The entire array has a single name. Each value has a numeric index. 79 87 94 82 67 98 87 81 74 91. scores. Arrays. An array is an ordered list of values. 0 1 2 3 4 5 6 7 8 9.

lavey
Download Presentation

Chapter 7

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 7 Arrays…

  2. The entire array has a single name Each value has a numeric index 79 87 94 82 67 98 87 81 74 91 scores Arrays • An array is an ordered list of values 0 1 2 3 4 5 6 7 8 9 An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9

  3. Arrays • A particular value in an array is referenced using the array name followed by the index in brackets • For example, the expression scores[2] refers to the value 94 (the 3rd value in the array) • That expression represents a place to store a single integer and can be used wherever an integer variable can be used

  4. Arrays • For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]);

  5. Arrays • The values held in an array are called array elements • An array stores multiple values of the same type – the element type • The element type can be a primitive type or an object reference • Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. • In Java, the array itself is an object that must be instantiated

  6. 79 scores 87 94 82 67 98 87 81 74 91 Arrays • Another way to depict the scores array:

  7. Declaring Arrays • The scores array could be declared as follows: int[] scores = new int[10]; • The type of the variable scores is int[] (an array of integers) • Note that the array type does not specify its size, but each object of that type has a specific size • The reference variable scores is set to a new array object that can hold 10 integers • An array is an object, therefore all the values are initialized to default ones (here 0)

  8. Declaring Arrays • Some other examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

  9. Using Arrays • The iterator version of the for loop can be used when processing array elements for (int score : scores) System.out.println (score); • This is only appropriate when processing all array elements from top (lowest index) to bottom (highest index) • See BasicArray.java(page 372)

  10. final int LIMIT = 15, MULTIPLE = 10; int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[5] = 999; // change one array value // Print the array values for (int value : list) System.out.print (value + " ");

  11. Bounds Checking • Once an array is created, it has a fixed size • An index used in an array reference must specify a valid element • That is, the index value must be in range 0 to N-1 • The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds • This is called automatic bounds checking

  12. problem Bounds Checking • For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 • If the value of count is 100, then the following reference will cause an exception to be thrown: System.out.println (codes[count]); • It’s common to introduce off-by-one errors when using arrays for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon;

  13. Bounds Checking • Each array object has a public constant called length that stores the size of the array • It is referenced using the array name: scores.length • Note that length holds the number of elements, not the largest index • See ReverseOrder.java(page 375) • See LetterCount.java(page 376)

  14. ReverseOrder Scanner scan = new Scanner (System.in); double[] numbers = new double[10]; System.out.println ("The size of the array: " + numbers.length); for (int index = 0; index < numbers.length; index++) { System.out.print ("Enter number " + (index+1) + ": "); numbers[index] = scan.nextDouble(); } System.out.println ("The numbers in reverse order:"); for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " ");

  15. Char type String st = "abcd"; for(int i =0; i < st.length (); i++ ) { char c = st.charAt (i); System.out.print(c); System.out.print(" "); System.out.print((int) c); System.out.print(" "); System.out.println(c - 'a'); } a 97 0 b 98 1 c 99 2

  16. Char Type for(int i =40; i < 130; i++) { System.out.print(i + ":\'" + (char) i + "\'\t"); if ((i+1) % 10 == 0) System.out.println(); } 40:'(' 41:')' 42:'*' 43:'+' 44:',' 45:'-' 46:'.' 47:'/' 48:'0' 49:'1' 50:'2' 51:'3' 52:'4' 53:'5' 54:'6' 55:'7' 56:'8' 57:'9' 58:':' 59:';' 60:'<' 61:'=' 62:'>' 63:'?' 64:'@' 65:'A' 66:'B' 67:'C' 68:'D' 69:'E' 70:'F' 71:'G' 72:'H' 73:'I' 74:'J' 75:'K' 76:'L' 77:'M' 78:'N' 79:'O' 80:'P' 81:'Q' 82:'R' 83:'S' 84:'T' 85:'U' 86:'V' 87:'W' 88:'X' 89:'Y' 90:'Z' 91:'[' 92:'\' 93:']' 94:'^' 95:'_' 96:'`' 97:'a' 98:'b' 99:'c' 100:'d' 101:'e' 102:'f' 103:'g' 104:'h' 105:'i' 106:'j' 107:'k' 108:'l' 109:'m' 110:'n' 111:'o' 112:'p' 113:'q' 114:'r' 115:'s' 116:'t' 117:'u' 118:'v' 119:'w' 120:'x' 121:'y' 122:'z' 123:'{' 124:'|' 125:'}' 126:'~' 127:'' 128:'?' 129:'?'

  17. Letter Count final int NUMCHARS = 26; Scanner scan = new Scanner (System.in); int[] upper = new int[NUMCHARS]; int[] lower = new int[NUMCHARS]; char current; // the current character being processed int other = 0; // counter for non-alphabetics System.out.println ("Enter a sentence:"); String line = scan.nextLine();

  18. Letter Count // Count the number of each letter occurence for (int ch = 0; ch < line.length(); ch++) { current = line.charAt(ch); if (current >= 'A' && current <= 'Z') upper[current-'A']++; else if (current >= 'a' && current <= 'z') lower[current-'a']++; else other++; }

  19. Letter Count // Print the results System.out.println (); for (int letter=0; letter < upper.length; letter++) { System.out.print ( (char) (letter + 'A') ); System.out.print (": " + upper[letter]); System.out.print ("\t\t" + (char) (letter + 'a') ); System.out.println (": " + lower[letter]); } System.out.println (); System.out.println ("Non-alphabetic characters: " + other);

  20. Alternate Array Syntax • The brackets of the array type can be associated with the element type or with the name of the array • Therefore the following two declarations are equivalent: float[] prices; float prices[]; • The first format generally is more readable and should be used

  21. Initializer Lists • An initializer list can be used to instantiate and fill an array in one step • The values are delimited by braces and separated by commas • Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

  22. Initializer Lists • Note that when an initializer list is used: • the new operator is not used • no size value is specified • The size of the array is determined by the number of items in the initializer list • An initializer list can be used only in the array declaration • SeePrimes.java(page 381)

  23. Primes int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19}; System.out.println ("Array length: " + primeNums.length); System.out.println ("The first few prime numbers are:"); for (int prime : primeNums) System.out.print (prime + " ");

  24. Arrays as Parameters • An entire array can be passed as a parameter to a method • Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other • Therefore, changing an array element within the method changes the original • An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type

  25. Arrays as Parameters public static void doubleValues(int[] x) { for (int i = 0; i < x.length; i++) { x[i] *= 2; } } int[] x = {1, 3, 5}; doubleValues(x); for(int val:x) System.out.print(val + " ");

  26. Arrays of Objects • Consider: class String3 { String value0, value1, value2; } String3 sts3 = new String3(); System.out.println(sts3.value0); // outputs null sts3.value0 = new String("abc");

  27. Arrays of Objects • The elements of an array can be object references • The following declaration reserves space to store 3 references to String objects String[] words = new String[3]; • It does NOT create the String objects themselves • Initially an array of objects holds null references • Each object stored in an array must be instantiated separately

  28. Previous Code using string array: String[] sts3 = new String[3]; System.out.println(sts3[0]); sts3[0] = new String("abc");

  29. Arrays of Objects • The words array when initially declared: - words - - • At this point, the following reference would throw a NullPointerException: System.out.println (words[0].length());

  30. “friendship” “loyalty” Arrays of Objects • After some String objects are created and stored in the array: words “honor”

  31. Arrays of Objects • Keep in mind that String objects can be created using literals • The following declaration creates an array object called verbs and fills it with four String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep"};

  32. Array of Objects • The following example creates an array of Grade objects, each with a string representation and a numeric lower bound • See GradeRange.java (page 384) • See Grade.java (page 385)

  33. Grade public class Grade { private String name; private int lowerBound; //----------------------------------------------------------------- // Constructor: Sets up this Grade object with the specified // grade name and numeric lower bound. //----------------------------------------------------------------- public Grade (String grade, int cutoff) { name = grade; lowerBound = cutoff; } //----------------------------------------------------------------- // Returns a string representation of this grade. //----------------------------------------------------------------- public String toString() { return name + "\t" + lowerBound; } }

  34. Grade[] grades = { new Grade("A", 95), new Grade("A-", 90), new Grade("B+", 87), new Grade("B", 85), new Grade("B-", 80), new Grade("C+", 77), new Grade("C", 75), new Grade("C-", 70), new Grade("D+", 67), new Grade("D", 65), new Grade("D-", 60), new Grade("F", 0) }; for (Grade letterGrade : grades) System.out.println (letterGrade);

  35. CD Collection • Let’s write methods that will help us maintain information about music CD’s. • Specifically, we want to keep track of the title, the artist name, and price of each CD. • Let’s keep these information in three different arrays, titles, artists, and prices. • The idea is the same location i is used for storing the information of CD number i in three different arrays. • Write methods for adding a new CD, deleting one given its title, and displaying information given its title.

  36. Example Use String[] ts = new String[100]; String[] as = new String[100]; double[] prices = new double[100]; int count = 0; CDCollection.addCD("title1", "artist1", 1,count, ts, as, prices); count++; CDCollection.addCD("title2", "artist2", 2,count, ts, as, prices); count++; CDCollection.addCD("title3", "artist3", 3,count, ts, as, prices); count++; CDCollection.printCD("title3", count, ts, as, prices); CDCollection.deleteCD("title2", count, ts, as, prices); count--; CDCollection.printCD("title2", count, ts, as, prices);

  37. public class CDCollection { public static void addCD(String title, String artist, double price, int count, String[] titles, String[] artists, double[] prices) { titles[count] = title; artists[count] = artist; prices[count] = price; } public static boolean deleteCD(String title,int count, String[] titles, String[] artists, double[] prices) { int loc = findCD(title, count, titles); if (loc == -1) return false; for(int i = loc + 1; i < count; i++) { titles[i-1] = titles[i]; artists[i-1] = artists[i]; prices[i-1] = prices[i]; } return true; }

  38. public static void printCD(String title,int count, String[] titles, String[] artists, double[] prices) { int loc = findCD(title, count, titles); if (loc == -1) System.out.println("CD not found"); else System.out.println("\n" + titles[loc] + " " + artists[loc] + " " + prices[loc]); } private static int findCD(String title,int count,String[] titles) { for(int i = 0; i < count; i++) if (titles[i].equals(title)) return i; return -1; }

  39. Notes • We can change the contents of the array, but not the primitive type int for count. • It is not convenient for the user to maintain the count variable himself. • One solution is to put the count into an int array • This way, the user can do : String[] ts = new String[100]; String[] as = new String[100]; double[] prices = new double[100]; int[] count = new int[1]; CDCollection.addCD("title1", "artist1", 1,count, ts, as, prices);

  40. public static void addCD(String title, String artist, double price, int[] count, String[] titles, String[] artists, double[] prices) { titles[count[0]] = title; artists[count[0]] = artist; prices[count[0]] = price; count[0]++; } public static boolean deleteCD(String title,int[] count, String[] titles, String[] artists, double[] prices) { int loc = findCD(title, count[0], titles); if (loc == -1) return false; for(int i = loc + 1; i < count[0]; i++) { titles[i-1] = titles[i]; artists[i-1] = artists[i]; prices[i-1] = prices[i]; } count[0]--; return true; }

  41. Notes • It is still inconvenient for the user to maintain the arrays and the count itself. • We can let the class contain the arrays itself

  42. Using static variables class CDCollection4 { private static int count = 0; private static String[] titles = new String[100]; private static String[] artists = new String[100]; private static double[] prices = new double[100]; public static void addCD(String title, String artist, double price) { titles[count] = title; artists[count] = artist; prices[count] = price; count++; }

  43. Using static variables CDCollection.addCD("title1", "artist1", 1); CDCollection.addCD("title2", "artist2", 2); CDCollection.addCD("title3", "artist3", 3); CDCollection.printCD("title3"); CDCollection.deleteCD("title2"); CDCollection.printCD("title2"); • Since the variables are static, and belong to the class (therefore there is only once copy), a program can only have one collection at a time.

  44. Using Objects • A better way is to make the variables and methods non-static, so that objects, not the class owns the information. So different objects will have their own arrays, letting one to use several collections at the same time • We also improve the code so that it grows the storage area as the number of CDs exceed the capacity.

  45. Using… CDCollection cc1 = new CDCollection(); CDCollection cc2 = new CDCollection(); cc1.addCD("title1", "artist1", 1); cc2.addCD("title2", "artist2", 2); cc1.addCD("title3", "artist3", 3); cc1.printCD("title3"); cc2.deleteCD("title2"); …

  46. Tunes CDCollection - collection : CD[] - count : int - totalCost : double + main (args : String[]) : void + addCD (title : String, artist : String, cost : double, tracks : int) : void + toString() : String - increaseSize() : void CD - title : String - artist : String - cost : double - tracks : int 1 * + toString() : String Arrays of Objects • A UML diagram for the Tunes program:

  47. CDCollection public class CDCollection { private CD[] collection; private int count; private double totalCost; //----------------------------------------------------------------- // Constructor: Creates an initially empty collection. //----------------------------------------------------------------- public CDCollection () { collection = new CD[100]; count = 0; totalCost = 0.0; }

  48. //----------------------------------------------------------------- //----------------------------------------------------------------- // Adds a CD to the collection, increasing the size of the // collection if necessary. //----------------------------------------------------------------- public void addCD (String title, String artist, double cost, int tracks) { if (count == collection.length) increaseSize(); collection[count] = new CD (title, artist, cost, tracks); totalCost += cost; count++; }

  49. public String toString() { NumberFormat fmt = NumberFormat.getCurrencyInstance(); String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; report += "My CD Collection\n\n"; report += "Number of CDs: " + count + "\n"; report += "Total cost: " + fmt.format(totalCost) + "\n"; report += "Average cost: " + fmt.format(totalCost/count); report += "\n\nCD List:\n\n"; for (int cd = 0; cd < count; cd++) report += collection[cd].toString() + "\n"; return report; }

  50. //----------------------------------------------------------------- //----------------------------------------------------------------- // Increases the capacity of the collection by creating a // larger array and copying the existing collection into it. //----------------------------------------------------------------- private void increaseSize () { CD[] temp = new CD[collection.length * 2]; for (int cd = 0; cd < collection.length; cd++) temp[cd] = collection[cd]; collection = temp; } }

More Related