Arrays - Review. Initializer Lists. The for-each Loop. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

Similar documents
CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays - Review. Two-Dimensional Arrays. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays - Review. Arrays as Parameters. Arrays as Parameters. Arrays and File Input. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

Arrays and File Input

Introduction to Arrays

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays and File Input

Chapter 7. Arrays are objects that help us organize large amounts of information

CSC 1051 Algorithms and Data Structures I. Final Examination December 20, Name: KEY. Question Value Score

Chapter 8 Arrays. Java Software Solutions. Foundations of Program Design Seventh Edition. John Lewis William Loftus

H212 Introduction to Software Systems Honors

2/2/18. Assignment 2 is due Wednesday 14 February at 11:59pm. Reading for Monday s lecture is the remainder of Chapter 7 and all of Chapter 8

CSC 1051 Data Structures and Algorithms I

Assignment 1 is due tonight at 11:59pm. Assignment 2 is due next Thursday at 11:59pm

COMP 202. Programming With Arrays

Selection Statements and operators

Selection Statements and operators

Iterators and File Input

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

COMP 202. Programming With Arrays

Arrays Chapter 7. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Selection and Repetition Revisited

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Selection and Repetition Revisited

CSC 1051 Algorithms and Data Structures I. Final Examination December 17, Name:

Selection and Repetition

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms and Conditionals

Java I/O and Control Structures

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

Java I/O and Control Structures Algorithms in everyday life

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name: KEY. Question Value Score

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

CSC 1051 Data Structures and Algorithms I

Where do objects come from? Good question!

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

2: Basics of Java Programming

7.3 Arrays of Strings (Objects) 7.3 Arrays of Strings (Objects) 7.3 Tunes.java. 7.3 Arrays of Objects 9/11/13. ! A UML diagram for the Tunes program

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Selection and Repetition

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

Using Classes and Objects

Arrays, Part 3: Multidimensional arrays

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

System.out.print("Enter sales for salesperson " + i + ": "); sales[i] = scan.nextint();

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

File I/O and Exceptions

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

Chapter. Let's explore some other fundamental programming concepts

Lecture 3: Variables and assignment

CSC 1051 Arrays - Review questions

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

&KDSWHU$UUD\VDQG9HFWRUV

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

Basics of Java Programming variables, assignment, and input

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

Chapter 3. Selections

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

Java Flow of Control

COE 212 Engineering Programming. Welcome to Exam II Monday May 13, 2013

COE 211/COE 212 Computer/Engineering Programming. Welcome to Exam II Thursday December 20, 2012

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

Happy Cinco de Mayo!!!!

Happy Cinco de Mayo!!!!

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

b[0] = 1 b[1] = 2 b[2] = 3 b[3] = 4 b[4] = 5 c[0] = 2 c[1] = 3 c[2] = 4 c[3] = 5 c[4] = 6

COE 212 Engineering Programming. Welcome to the Final Exam Monday May 18, 2015

Lab 13. Name: Checked:

CS Computers & Programming I Review_01 Dr. H. Assadipour

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Conditional Statements

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

Text User Interfaces. Keyboard IO plus

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

Introduction to Java (All the Basic Stuff)

Designing Classes part 2

Data Representation Classes, and the Java API

Object-Oriented Design. Chapter. Class Relationships. Classes in a software system can have various types of relationships to each other

Transcription:

Arrays, Part 2 Arrays - Review Declaration: double[] scores element type Instantiation: = new double[10]; CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus The entire array has a single name scores Initialization: scores[0] = 7.9; scores[1] = 8.7; scores[2] = 9.4; scores[3] = 8.2; scores[4] = 6.7; scores[5] = 9.8; scores[6] = 8.7; scores[7] = 8.1; scores[8] = 7.4; scores[9] = 9.1; index array element scores[2] 0 1 2 3 4 5 6 7 8 9 7.9 8.7 9.4 8.2 6.7 9.8 8.7 8.1 7.4 9.1 Size of array scores.length 10 Initializer Lists Alternative way to declare, instantiate, and initialize an array. For example: int[] ratings = 4, 3, 3, 1, 4, 2, 1, 0, 3, 4; char[] grades = 'A', 'B', 'C', 'D', F'; NOTE: the new operator is not used size of array is determined by the number of items listed 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 The for-each Loop A simple way of processing every array element: for (double score : scores) System.out.println (score); NOTE: Only appropriate when processing all array elements starting at index 0 It can't be used to set the array values try this with the vowel array vowel 0 1 2 3 4 a e i o u Dr. Papalaskari 1

Another example String[] animals = "dog", "cat", "mouse", "fox"; for (String word : animals) System.out.println ("The " + word + " ate the cake" ); NOTE: Only appropriate when processing all array elements starting at index Try this: Use the for each loop to scan through an array of int containing ratings (range: 0-4) and count up how many 4 s. int[] ratings = 4, 3, 3, 1, 4, 3, 1, 0, 3, 4; for (String word : animals) for (String otherword: animals) System.out.println ("The " + word + " ate the " + otherword); Try this: Repeat, but now count up the 0 s, 1 s, 4 s Use a separate array for this int[] ratings = 4, 3, 3, 1, 4, 3, 1, 0, 3, 4; More array examples (see textbook): BasicArray.java Primes.java ReverseOrder.java LetterCount.java Dr. Papalaskari 2

ReverseOrder.java Author: Lewis/Loftus Demonstrates array index processing. import java.util.scanner; public class ReverseOrder Reads a list of numbers from the user, storing them in an array, then prints them in the opposite order. public static void main (String[] args) Scanner scan = new Scanner (System.in); double[] numbers = new double[10]; 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] + " "); System.out.println ("The size of the array: " + numbers.length); Sample Run The size of the array: 10 Enter number 1: 18.36 Enter number 2: 48.9 Enter number 3: 53.5 for (int index = 0; index < numbers.length; index++) Enter number 4: 29.06 Enter number System.out.print 5: 72.404 ("Enter number " + (index+1) + ": "); Enter number numbers[index] 6: 34.8 = scan.nextdouble(); Enter number 7: 63.41 Enter number 8: 45.55 Enter number System.out.println 9: 69.0 ("The numbers in reverse order:"); Enter number 10: 99.18 for (int index = numbers.length-1; index >= 0; index--) The numbers in reverse order: System.out.print (numbers[index] + " "); 99.18 69.0 45.55 63.41 34.8 72.404 29.06 53.5 48.9 18.36 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 Another example: Computing letter frequency counts Sample run: Enter a sentence: In Casablanca, Humphrey Bogart never says "Play it again, Sam." A: 0 a: 10 B: 1 b: 1 C: 1 c: 1 D: 0 d: 0 E: 0 e: 3 Let s write a program to do this Dr. Papalaskari 3

Arrays, Part 2 LetterCount.java Author: Lewis/Loftus Demonstrates the relationship between arrays and strings. import java.util.scanner; public class LetterCount Reads a sentence from the user and counts the number of uppercase and lowercase letters contained in it. public static void main (String[] args) 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(); 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++; 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); Sample Run Enter a sentence: In Casablanca, Humphrey Bogart never says "Play it again, Sam." A: 0 Print a: the 10 results B: 1 System.out.println b: 1 (); C: 1 for (int letter=0; c: 1 letter < upper.length; letter++) D: 0 d: 0 E: 0 System.out.print e: 3 ( (char) (letter + 'A') ); F: 0 System.out.print f: 0 (": " + upper[letter]); System.out.print ("\t\t" + (char) (letter + 'a') ); G: 0 g: 2 Sample Run (d) System.out.println (": " + lower[letter]); H: 1 h: 1 R: 0 r: 3 I: 1 i: 2 S: 1 s: 3 J: 0 System.out.println j: 0 (); T: 0 t: 2 K: 0 System.out.println k: 0 ("Non-alphabetic characters: " + other); U: 0 u: 1 L: 0 l: 2 V: 0 v: 1 M: 0 m: 2 W: 0 w: 0 N: 0 n: 4 X: 0 x: 0 O: 0 o: 1 Y: 0 y: 3 P: 1 p: 1 Z: 0 z: 0 Q: 0 q: 0 Non-alphabetic characters: 14 Arrays as Parameters An entire array can be passed as a parameter to a method (just like any other object). For example: Draws a triangle and a V-shape using polygons and polylines. public void paintcomponent(graphics page) super.paintcomponent(page); int[] xpoints = 100, 120, 150; int[] ypoints = 150, 40, 110; Assumes a definition for method average(), for example: page.setcolor(color.cyan); page.fillpolygon(xpoints, ypoints, xpoints.length); page.setcolor(color.red); page.drawpolyline(xpoints, ypoints, xpoints.length); see TrianglePanel.java Dr. Papalaskari 4

Example: A method that adds 3 to the value of each element in an array of type int[]. Try this: Write a method that adds n (an int) to the 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, using the updated array xpoints Command-Line Arguments It turns out we have been using arrays as parameters all along! public static void main (String[] args) Command-Line Arguments It turns out we have been using arrays as parameters all along! public class Test 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 Dr. Papalaskari 5

What does it mean to copy an array? Suppose we have two arrays: int[] a = 147, 323, 89, 933; int[] b = 100, 200, 300, 400; Copying elements vs. copying array variables: for (int i=0; i<a.length; i++) a[i] = b[i]; Afterwards, what is the effect of the following? a[1] = 1000; b[2] = 2000; a = b; 1) Copying elements: a b What changes? 0 1 2 3 147 323 89 933 0 1 2 3 100 200 300 400 for (int i=0; i<a.length; i++) a[i] = b[i]; a[1] = 1000; b[2] = 2000; 2) Copying array variables: a b What 0 1 2 3 147 323 89 933 0 1 2 3 100 200 300 400 a = b; changes? a[1] = 1000; b[2] = 2000; Array parameters revisited How is using an array as a parameter like copying an array? Draws a triangle and a V-shape using polygons and polylines. public void paintcomponent(graphics page) super.paintcomponent(page); int[] xpoints = 100, 120, 150; int[] ypoints = 150, 40, 110; page.setcolor(color.cyan); page.fillpolygon(xpoints, ypoints, xpoints.length); addthree(xpoints);" page.setcolor(color.red); page.drawpolyline(xpoints, ypoints, xpoints.length); public void addthree(int[] a) for (int i = 0; i < a.length; i++) a[i] += 3; Dr. Papalaskari 6

Managing a collection of objects Example: a Movie database (collection of DVD objects) DVD.java Author: Lewis/Loftus/Papalaskari Represents a DVD video disc. (*** 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; Returns a string description of this DVD. public String tostring() NumberFormat fmt = NumberFormat.getCurrencyInstance(); String description; description = fmt.format(cost) + "\t" + year + "\t"; description += title + "\t" + director; Test client create a few DVDs, print their info: TestDVD.java Author: M A Papalaskari Test client for DVD.java public class TestDVD Creates some DVD objects and prints their info public static void main(string[] args) if (bluray) description += "\t" + "Blu-Ray"; return description; DVD one = new DVD("Casablanca", "Michael Curtiz", 1942, 19.95, false); DVD two = new DVD("District 9", "Neill Blomkamp", 2009, 19.95, false); DVD three = new DVD("Iron Man", "Jon Favreau", 2008, 15.95, false); System.out.println (one); System.out.println (two); System.out.println (three); Dr. Papalaskari 7

What if we want to store more DVDs? MyTenMovies.java Author: M A Papalaskari Test client for DVD.java public class MyTenMovies Creates some DVD objects and prints their info public static void main(string[] args) DVD[] list = new DVD[10]; Use an array of DVD objects: list[0] DVD one = new DVD("Casablanca", "Michael Curtiz", 1942, 19.95, false); 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); System.out.println (one); for System.out.println (DVD item: list) (two); System.out.println System.out.println (three); (item); Let s store the data in a tab-delimited file: 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 All About Eve Joseph Mankiewicz 1950 17.50 false The Matrix Andy & Lana Wachowski 1999 19.95 true Iron Man 2 Jon Favreau 2010 22.99 false Casablanca Michael Curtiz 1942 19.95 false Client code fragment to input lines from file: Scanner filescan = new Scanner(new File(args[0])); int i = 0; while ( filescan.hasnextline() && i < list.length) list[i] = new DVD(fileScan.nextLine()); i++; We need constructor to handle this Remember, we also need: import java.util.scanner; import java.io.*; throws IOException where do these go??? The current DVD constructor CANNOT be used in this manner: list[i] = new DVD(fileScan.nextLine()); 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 Constructor: Creates All a new About DVD Eve with Joseph the specified Mankiewicz information. 1950 17.50 false public DVD(String title, The String Matrix director, Andy int & Lana year, Wachowski double cost, 1999 boolean 19.95 true bluray) 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; Another constructor: Creates a new DVD with the specified String. public DVD(String data) Scanner scan = new Scanner(data); 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.java Next: A collection of DVD s that can grow to accommodate as many items as needed! No limit like this: DVD[] list = new DVD[10]; Dr. Papalaskari 8

Managing a collection of objects Example: a Movie database (collection of DVD objects) Movies.java Author: Lewis/Loftus/Papalaskari Demonstrates the use of DVDCollection. import java.util.scanner; import java.io.*; Movies.java DVDCollection.java public class Movies Creates a DVDCollection object and adds some DVDs to it. Prints reports on the status of the collection. 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()); DVD.java System.out.println(movies); Movies.java Author: Lewis/Loftus/Papalaskari Demonstrates the use of DVDCollection. import java.util.scanner; import java.io.*; Output public class ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Movies My DVD Collection Creates Number a of DVDCollection DVDs: 5 object and adds some DVDs to it. Prints reports Total on cost: the $98.30 status of the collection. Average cost: $19.66 public static void main(string[] args) throws IOException DVD List: Scanner filescan = new Scanner(new File(args[0])); DVDCollection $24.95 1972 movies The = Godfather new DVDCollection(); Francis Ford Coppala Blu-Ray $19.95 2009 District 9 Neill Blomkamp while $15.95 ( filescan.hasnextline()) 2008 Iron Man Jon Favreau movies.adddvd(filescan.nextline()); $17.50 1950 All About Eve Joseph Mankiewicz $19.95 1999 The Matrix Andy & Lana Wachowski Blu-Ray System.out.println(movies); DVDCollection.java Author: Lewis/Loftus/Papalaskari Represents a collection of DVD objects (*** modified from textbook version ***) import java.text.numberformat; public class DVDCollection private DVD[] collection; private int count; Constructor: Creates an initially empty collection. public DVDCollection() collection = new DVD[100]; count = 0; Dr. Papalaskari 9

Adds a DVD to the collection, using information from a String and increasing the size of the collection array if necessary. public void adddvd(string info) if (count == collection.length) increasesize(); collection[count] = new DVD(info); count++; Adds a DVD to the collection, increasing the size of the collection array if necessary. public void adddvd(string title, String director, int year, double cost, boolean bluray) if (count == collection.length) increasesize(); Returns a report describing the DVD collection. public String tostring() NumberFormat fmt = NumberFormat.getCurrencyInstance(); String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; report += "My DVD Collection\n\n"; report += "Number of DVDs: " + count + "\n"; report += "\n\ndvd List:\n\n"; for (int i = 0; i < count; i++) report += collection[i].tostring() + "\n"; return report; collection[count] = new DVD(title, director, year, cost, bluray); count++; 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; Dr. Papalaskari 10