Quick viewing(Text Mode)

Arrays, Part 2 CSC 1051 Villanova University

Arrays, Part 2 CSC 1051 Villanova University

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

CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University

2) Copying array variables: Array parameters revisited • How is using an array as a parameter like “copying an array”? a 0 1 2 3 // Draws a triangle and a V-shape using polygons and polylines. public void paintComponent(Graphics page) { 147 323 89 933 super.paintComponent(page);

int[] xPoints = {100, 120, 150}; b 0 1 2 3 int[] yPoints = {150, 40, 110};

page.setColor(Color.cyan); 100 200 300 400 page.fillPolygon(xPoints, yPoints, xPoints.length);

addThree(xPoints); page.setColor(Color.red); What a = b; page.drawPolyline(xPoints, yPoints, xPoints.length); changes? a[1] = 1000; } public void addThree(int[] a) b[2] = 2000; { for (int i = 0; i < a.length; i++) a[i] += 3; CSC 1051 M.A. Papalaskari, Villanova University } CSC 1051 M.A. Papalaskari, Villanova University

Dr. Papalaskari 6 Arrays, Part 2 CSC 1051 Villanova University

//******************************************************************** Managing a collection of objects // DVD.java Author: Lewis/Loftus/Papalaskari // // Represents a DVD video disc. • Example: a Movie database (collection of DVD objects) // (*** modified from textbook version ***) // ********************************************************************im port java.text.NumberFormat;

public class DVD { private String title, director; private int year; private double cost; private boolean bluRay;

// Constructor: Creates a new DVD with the specified information. public DVD(String title, String director, int year, double cost, boolean bluRay) { this.title = title; this.director = director; this.year = year; this.cost = cost; this.bluRay = bluRay; }

continue CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University

Test client – create a few DVDs, print their info: //******************************************************************** // TestDVD.java Author: M A Papalaskari continue // // Test client for DVD.java // Returns a string description of this DVD. //******************************************************************** public String toString() { public class TestDVD NumberFormat fmt = NumberFormat.getCurrencyInstance(); { //------String description; // Creates some DVD objects and prints their info //------description = fmt.format(cost) + "\t" + year + "\t"; public static void main(String[] args) description += title + "\t" + director; {

if (bluRay) description += "\t" + "Blu-Ray"; DVD one = new DVD("Casablanca", "Michael Curtiz", 1942, 19.95, false);

return description; DVD two = new DVD("District 9", "Neill Blomkamp", 2009, 19.95, false); } DVD three = new DVD("", "", 2008, 15.95, false); } System.out.println (one); System.out.println (two); CSC 1051 M.A. Papalaskari, Villanova University System.out.println (three); CSC 1051 M.A. Papalaskari, Villanova University } }

Dr. Papalaskari 7 Arrays, Part 2 CSC 1051 Villanova University

What if we want to store more DVDs? Let’s store the data in a tab-delimited file: • Use an array of DVD objects: The Godfather 1972 24.95 true District 9 Neill Blomkamp 2009 19.95 false //******************************************************************** // MyTenMovies.java Author: M A Papalaskari Iron Man Jon Favreau 2008 15.95 false // All About Eve Joseph Mankiewicz 1950 17.50 false // Test client for DVD.java //******************************************************************** The Matrix Andy & Lana Wachowski 1999 19.95 true Jon Favreau 2010 22.99 false public class MyTenMoviesMyTenMovies Casablanca Michael Curtiz 1942 19.95 false { //------// Creates some DVD objects and prints their info Client code fragment to input lines from file: //------public static void main(String[] args) Scanner fileScan = new Scanner(new File(args[0])); { DVD[] list = new DVD[10]; int i = 0; list[0]DVD one = new DVD("Casablanca", "Michael Curtiz", 1942, 19.95, false); while ( fileScan.hasNextLine() && i < list.length) list[1]DVD two = new DVD("District 9", "Neill Blomkamp", 2009, 19.95, false); { list[2]DVD three = new DVD("Iron Man", "Jon Favreau", 2008, 15.95, false); list[i] = new DVD(fileScan.nextLine()); i++; Remember, we also need: System.out.println (one); } • import java.util.Scanner; forSystem.out.println (DVD item: list) (two); • import java.io.*; System.out.println (item); We need constructor to handle this • throws IOException System.out.println (three); whereCSC do 1051these M.A. go??? Papalaskari, Villanova University } }

The current DVD constructor CANNOT be used in this manner: list[i] = new DVD(fileScan.nextLine()); Next: A collection of DVD’s that can The Godfather Francis Ford Coppola 1972 24.95 true District 9 Neill Blomkamp 2009 19.95 false Iron Man Jon Favreau 2008 15.95 false grow to accommodate as many items // Constructor: CreatesAll a newAbout DVD Eve with Joseph the specified Mankiewicz information. 1950 17.50 false public DVD(String title,The String Matrix director, Andy int & Lanayear, Wachowski double cost, 1999 boolean 19.95 truebluRay ) as needed! { Iron Man 2 Jon Favreau 2010 22.99 false this.title = title;Casablanca Michael Curtiz 1942 19.95 false this.director = director; old constructor this.year = year; this.cost = cost; this.bluRay = bluRay; } • No limit like this: // Another constructor: Creates a new DVD with the specified String. public DVD(String data) { Scanner scan = new Scanner(data); DVD[] list = new DVD[10]; scan.useDelimiter("\t"); title = scan.next(); director = scan.next(); new constructor year = scan.nextInt(); cost = scan.nextDouble(); bluRay = scan.nextBoolean(); }

add new constructor to DVD class and try with MyTenMovies.javaCSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University

Dr. Papalaskari 8 Arrays, Part 2 CSC 1051 Villanova University

//******************************************************************** // Movies.java Author: Lewis/Loftus/Papalaskari Managing a collection of objects // // Demonstrates the use of DVDCollection. • Example: a Movie database (collection of DVD objects) //******************************************************************** import java.util.Scanner; import java.io.*;

public class Movies { //------// Creates a DVDCollection object and adds some DVDs to it. Prints // reports on the status of the collection. Movies.java //------DVDCollection.java public static void main(String[] args) throws IOException { Scanner fileScan = new Scanner(new File(args[0])); DVDCollection movies = new DVDCollection();

while ( fileScan.hasNextLine()) movies.addDVD(fileScan.nextLine());

System.out.println(movies); DVD.java } }

CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // Movies.java Author: Lewis/Loftus/Papalaskari //******************************************************************** // // DVDCollection.java Author: Lewis/Loftus/Papalaskari // Demonstrates the use of DVDCollection. // //******************************************************************** // Represents a collection of DVD objects import java.util.Scanner; // (*** modified from textbook version ***) //******************************************************************** import java.io.*; Output import java.text.NumberFormat; public class~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Movies { My DVD Collection public class DVDCollection //------{ // CreatesNumber a ofDVDCollection DVDs: 5 object and adds some DVDs to it. Prints private DVD[] collection; // reportsTotal oncost: the $98.30status of the collection. private int count;

//------Average cost: $19.66 //------public static void main(String[] args) throws IOException // Constructor: Creates an initially empty collection. { DVD List: //------Scanner fileScan = new Scanner(new File(args[0])); public DVDCollection() DVDCollection$24.95 1972 movies The = Godfathernew DVDCollection Francis(); Ford Coppala Blu-Ray { $19.95 2009 District 9 Neill Blomkamp collection = new DVD[100]; while$15.95 ( fileScan.hasNextLine 2008 Iron Man ()) Jon Favreau count = 0; } movies.addDVD$17.50 1950 (fileScan.nextLine All About Eve Joseph()); Mankiewicz $19.95 1999 The Matrix Andy & Lana Wachowski Blu-Ray System.out.println (movies); } continue }

CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University

Dr. Papalaskari 9 Arrays, Part 2 CSC 1051 Villanova University

continue continue //------// Adds a DVD to the collection, using information from a String //------// and increasing the size of the collection array if necessary. // Returns a report describing the DVD collection. //------//------public void addDVD(String info) public String toString() { { if (count == collection.length) NumberFormat fmt = NumberFormat.getCurrencyInstance(); increaseSize(); String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; collection[count] = new DVD(info); report += "My DVD Collection\n\n"; count++; } report += "Number of DVDs: " + count + "\n"; report += "\n\nDVD List:\n\n"; //------// Adds a DVD to the collection, increasing the size of the for (int i = 0; i < count; i++) // collection array if necessary. report += collection[i].toString() + "\n"; //------public void addDVD(String title, String director, int year, return report; double cost, boolean bluRay) } { if (count == collection.length) continue increaseSize();

collection[count] = new DVD(title, director, year, cost, bluRay); count++; }

continue CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 M.A. Papalaskari, Villanova University

continue

//------// Increases the capacity of the collection by creating a // larger array and copying the existing collection into it. //------private void increaseSize() { DVD[] temp = new DVD[collection.length * 2];

for (int i = 0; i < collection.length; i++) temp[i] = collection[i];

collection = temp; } }

CSC 1051 M.A. Papalaskari, Villanova University

Dr. Papalaskari 10