Arrays, Part 2 CSC 1051 Villanova University
Total Page:16
File Type:pdf, Size:1020Kb
Arrays, Part 2 CSC 1051 Villanova University Arrays - Review element type • Instantiation: Arrays, Part 2 • Declaration: double[] scores = new double[10]; The entire array array element CSC 1051 – Data Structures and Algorithms I has a single name index scores[2] Dr. Mary-Angela Papalaskari 0 1 2 3 4 5 6 7 8 9 Department of Computing Sciences scores Villanova University • Initialization : 7.9 8.7 9.4 8.2 6.7 9.8 8.7 8.1 7.4 9.1 scores[0] = 7.9; scores[1] = 8.7; Course website: scores[2] = 9.4; Size of array scores[3] = 8.2; www.csc.villanova.edu/~map/1051/ scores[4] = 6.7; scores[5] = 9.8; scores[6] = 8.7; scores.length scores[7] = 8.1; Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus scores[8] = 7.4; 10 scores[9] = 9.1; CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Initializer Lists The “for-each” Loop • Alternative way to declare, instantiate, and initialize • A simple way of processing every array element: an array. For example: for (double score : scores) int[] ratings = {4, 3, 3, 1, 4, 2, 1, 0, 3, 4}; System.out.println (score); char[] grades = {'A', 'B', 'C', 'D', ’F'}; NOTE: • Only appropriate when processing all array elements starting at index 0 • NOTE: – the new operator is not used • It can't be used to set the array values – size of array is determined by the number of items listed vowel 0 1 2 3 4 – can only be used in the array declaration vowel 0 1 2 3 4 try this with the vowel array ‘a’ ‘e’ ‘i’ ‘o’ ‘u’ try this with the vowel array ‘a’ ‘e’ ‘i’ ‘o’ ‘u’ CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Dr. Papalaskari 1 Arrays, Part 2 CSC 1051 Villanova University Another example Try this: Use the “for each” loop to scan through an array of int containing ratings (range: 0 - 4) String[] animals = {"dog", "cat", "mouse", "fox"}; and count up how many 4’s. for (String word : animals) System.out.println ("The " + word + " ate the cake" ); int [] ratings = {4, 3, 3, 1, 4, 3, 1, 0, 3, 4}; NOTE: • Only appropriate when processing all array elements starting at index for (String word : animals) for (String otherWord: animals) System.out.println ("The " + word + " ate the " + otherWord); CSC 1051 M.A. Papalaskari, Villanova University Try this: Repeat, but now count up the 0’s, 1’s,… More array examples (see textbook): 4’s – Use a separate array for this • BasicArray.java int [] ratings = {4, 3, 3, 1, 4, 3, 1, 0, 3, 4}; • Primes.java • ReverseOrder.java • LetterCount.java CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Dr. Papalaskari 2 Arrays, Part 2 CSC 1051 Villanova University //******************************************************************** // ReverseOrder.java Author: Lewis/Loftus // // Demonstrates array index processing. //******************************************************************** continue import java.util.Scanner; for (int index = 0; index < numbers.length; index++) { public class ReverseOrder System.out.print ("Enter number " + (index+1) + ": "); { numbers[index] = scan.nextDouble(); //----------------------------------------------------------------- } // Reads a list of numbers from the user, storing them in an // array, then prints them in the opposite order. System.out.println ("The numbers in reverse order:"); //----------------------------------------------------------------- public static void main (String[] args) for (int index = numbers.length-1; index >= 0; index--) { System.out.print (numbers[index] + " "); Scanner scan = new Scanner (System.in); } } double[] numbers = new double[10]; System.out.println ("The size of the array: " + numbers.length); continue CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Another example: Sample Run The size of the array: 10 Computing letter frequency counts Enter number 1: 18.36 Entercontinue number 2: 48.9 Sample run: Enter number 3: 53.5 for (int index = 0; index < numbers.length; index++) Enter number 4: 29.06 { Enter a sentence: Enter number System.out.print 5: 72.404 ("Enter number " + (index+1) + ": "); Enter number numbers[index] 6: 34.8 = scan.nextDouble(); In Casablanca, Humphrey Bogart never says Enter number} 7: 63.41 Enter number 8: 45.55 "Play it again, Sam." Enter numberSystem.out.println 9: 69.0 ("The numbers in reverse order:"); Enter number 10: 99.18 The numbers for (int in indexreverse = numbers.length-1; order: index >= 0; index--) A: 0 a: 10 System.out.print (numbers[index] + " "); Let’s write a 99.18 } 69.0 45.55 63.41 34.8 72.404 29.06 53.5 48.9 18.36 B: 1 b: 1 } C: 1 c: 1 program to D: 0 d: 0 do this E: 0 e: 3 places numbers in an array, then prints them out backward … alternatively, we could place the numbers in the array backward and then print them forward … CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Dr. Papalaskari 3 Arrays, Part 2 CSC 1051 Villanova University continue System.out.println ("Enter a sentence:"); //******************************************************************** // LetterCount.java Author: Lewis/Loftus String line = scan.nextLine(); // // Demonstrates the relationship between arrays and strings. // Count the number of each letter occurence //******************************************************************** for (int ch = 0; ch < line.length(); ch++) { import java.util.Scanner; current = line.charAt(ch); if (current >= 'A' && current <= 'Z') public class LetterCount upper[current-'A']++; { else if (current >= 'a' && current <= 'z') //----------------------------------------------------------------- // Reads a sentence from the user and counts the number of lower[current-'a']++; // uppercase and lowercase letters contained in it. else //----------------------------------------------------------------- other++; public static void main (String[] args) } // Print the results { final int NUMCHARS = 26; System.out.println (); for (int letter=0; letter < upper.length; letter++) Scanner scan = new Scanner (System.in); { System.out.print ( (char) (letter + 'A') ); int[] upper = new int[NUMCHARS]; System.out.print (": " + upper[letter]); int[] lower = new int[NUMCHARS]; System.out.print ("\t\t" + (char) (letter + 'a') ); System.out.println (": " + lower[letter]); char current; // the current character being processed } int other = 0; // counter for non-alphabetics System.out.println (); continue System.out.println ("Non-alphabetic characters: " + other); } } CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Sample Run Arrays as Parameters Enter a sentence: In Casablanca, Humphrey Bogart never says "Play it again, Sam." continue • An entire array can be passed as a parameter to a method (just like any other object). For example: A: 0 // Print a:the 10results B: 1 System.out.println b: 1 (); C: 1 for (int letter=0;c: 1 letter < upper.length; letter++) // Draws a triangle and a V-shape using polygons and polylines. D: 0 { d: 0 public void paintComponent(Graphics page) E: 0 System.out.print e: 3 ( (char) (letter + 'A') ); { F: 0 System.out.print f: 0 (": " + upper[letter]); super.paintComponent(page); G: 0 System.out.print g: 2 ("\t\t"Sample + (char) (letterRun (continued) + 'a') ); System.out.println (": " + lower[letter]); H: 1 } h: 1 R: 0 r: 3 int[] xPoints = {100, 120, 150}; I: 1 i: 2 S: 1 s: 3 int[] yPoints = {150, 40, 110}; J: 0 System.out.println j: 0 (); T: 0 t: 2 • Assumes a definition for method average(), for example: K: 0 System.out.println k: 0 ("Non-alphabeticU: 0 characters: u: 1 " + other); page.setColor(Color.cyan); } L: 0 l: 2 V: 0 v: 1 page.fillPolygon(xPoints, yPoints, xPoints.length); } M: 0 m: 2 W: 0 w: 0 N: 0 n: 4 X: 0 x: 0 page.setColor(Color.red); O: 0 o: 1 Y: 0 y: 3 page.drawPolyline(xPoints, yPoints, xPoints.length); P: 1 p: 1 Z: 0 z: 0 } Q: 0 q: 0 Non-alphabetic characters: 14 continue see TrianglePanel.java CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Dr. Papalaskari 4 Arrays, Part 2 CSC 1051 Villanova University Example: A method that adds 3 to the value of each Try this: Write a method that adds n (an int) to the element in an array of type int[]. value of each element in an array of type int[]. public void addThree(int[] a) { for (int i = 0; i < a.length; i++) a[i] += 3; } Try this method with the TrianglePanel: • invoke it with the array xPoints • add code to draw another triangle in a different color, CSC 1051 M.A. Papalaskari, Villanova University using the updated array xPoints CSC 1051 M.A. Papalaskari, Villanova University Command-Line Arguments Command-Line Arguments • It turns out we have been using arrays as • It turns out we have been using arrays as parameters all along! parameters all along! public class Test { public static void main (String[] args) public static void main (String[] args) { System.out.println (); System.out.println (" " + args[0]); System.out.println (" " + args[1]); } } • These values come from command-line arguments that are provided when the interpreter is invoked • jGrasp calls them “Run Arguments” CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University Dr. Papalaskari 5 Arrays, Part 2 CSC 1051 Villanova University What does it mean to “copy an array”? 1) Copying elements: • Suppose we have two arrays: a 0 1 2 3 int[] a = {147, 323, 89, 933}; int[] b = {100, 200, 300, 400}; 147 323 89 933 Copying elements vs. copying array variables: 0 1 2 3 b 100 200 300 400 for (int i=0; i<a.length; i++) a = b; a[i] = b[i]; What for (int i=0; i<a.length; i++) Afterwards, what is the effect of the following? changes? a[i] = b[i]; a[1] = 1000; a[1] = 1000; b[2] = 2000; b[2] = 2000; CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A.