Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Fields, Constructors, Methods
Lab 10: Bank Account II Transaction List, error checking & aggregation.
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Using Collections. Review of Collections Using an ArrayList It increases its capacity as necessary. It keeps a private count ( size() accessor). It keeps.
Grouping Objects 3 Iterators, collections and the while loop.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
More sophisticated behavior Using library classes to implement some more advanced functionality 4.0.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
Grouping Objects 1 Introduction to Collections.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Grouping objects Collections and iterators. 04/11/2004Lecture 4: Grouping Objects2 Main concepts to be covered Collections Loops Iterators Arrays.
More sophisticated behavior Using library classes to implement some more advanced functionality 3.0.
Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Writing Methods Using if, loops, and variables to implement algorithms Copyright © 2012 Pearson Education, Inc.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
Outline ArrayList Searching Sorting Copyright © 2012 Pearson Education, Inc.
Object Oriented Design: Identifying Objects
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 2.0.
Grouping objects Arrays, Collections and Iterators 1.0.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Grouping objects Introduction to collections 5.0.
1 CSC 221: Computer Programming I Fall 2004 Lists, data access, and searching  ArrayList class  ArrayList methods: add, get, size, remove  example:
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
Chapter 6. else-if & switch Copyright © 2012 Pearson Education, Inc.
5-1 Chapter 5: Conditionals and Loops Topics: –Boolean expressions –Conditional statements –Increment and Decrement Operators (Chapter 2.4) –Repetition.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 1.0.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Using Classes and Objects (Chapter 3) Copyright © 2012 Pearson Education, Inc.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Grouping objects Introduction to collections 5.0.
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Using Classes and Objects We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: object creation and.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Chapter 8: Understanding Collections Textbook: Chapter 4.
Objects First with Java CITS1001 week 4
Project 1.
Objects First with Java Introduction to collections
Using Classes and Objects (Chapter 3)
Functional Processing of Collections (Advanced)
Chapter 6 More Conditionals and Loops
The ArrayList Class An ArrayList object stores a list of objects, and is often processed using a loop The ArrayList class is part of the java.util package.
ITunes Lab Copyright © 2012 Pearson Education, Inc.
Object Oriented Programming in java
Collections and iterators
The Random Class The Random class is part of the java.util package
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Improving structure with inheritance
Collections and iterators
Presentation transcript:

Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.

Conditionals and Loops So far, we’ve looked at: –making decisions with if –how to compare data –Boolean expressions Today we’ll look at: –Generating lists of random numbers –Storing lists (collections) of objects –repeat processing steps in a loop Copyright © 2012 Pearson Education, Inc.

RANDOM Copyright © 2012 Pearson Education, Inc.

The Random Class The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // RandomNumbers.java Author: Lewis/Loftus // // Demonstrates the creation of pseudo-random numbers using the // Random class. //******************************************************************** import java.util.Random; public class RandomNumbers { // // Generates random numbers in various ranges. // public static void main (String[] args) { Random generator = new Random(); int num1; float num2; num1 = generator.nextInt(); System.out.println ("A random integer: " + num1); num1 = generator.nextInt(10); System.out.println ("From 0 to 9: " + num1); continued

Copyright © 2012 Pearson Education, Inc. continued num1 = generator.nextInt(10) + 1; System.out.println ("From 1 to 10: " + num1); num1 = generator.nextInt(15) + 20; System.out.println ("From 20 to 34: " + num1); num1 = generator.nextInt(20) - 10; System.out.println ("From -10 to 9: " + num1); num2 = generator.nextFloat(); System.out.println ("A random float (between 0-1): " + num2); num2 = generator.nextFloat() * 6; // 0.0 to num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); } Sample Run A random integer: From 0 to 9: 0 From 1 to 10: 3 From 20 to 34: 30 From -10 to 9: -4 A random float (between 0-1): From 1 to 6: 3

Examples – code to outcome Copyright © 2012 Pearson Education, Inc. Given a Random object named gen, what range of values are produced by the following expressions? gen.nextInt(25) gen.nextInt(6) + 1 gen.nextInt(100) + 10 gen.nextInt(50) gen.nextInt(10) – 5 gen.nextInt(22) + 12 Range? 0 to 24 1 to 6 10 to to to 4 12 to 33

Examples – outcome to code Copyright © 2012 Pearson Education, Inc. Write an expression that produces a random integer in the following ranges: gen.nextInt(13) gen.nextInt(20) + 1 gen.nextInt(6) + 15 gen.nextInt(11) – 10 Range 0 to 12 1 to to to 0

COLLECTIONS & LOOPS Copyright © 2012 Pearson Education, Inc.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Grouping (i.e., collecting) objects Many applications involve collections of objects: –Personal organizers. –Library catalogs. –Student-record system. The number of items to be stored varies. –Items added. –Items deleted.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Example: A personal notebook Notes may be stored. Individual notes can be viewed. There is no limit to the number of notes. It will tell how many notes are stored. Consider a Notebook project.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling import java.util.ArrayList; /** *... */ public class Notebook { // Storage for an arbitrary number of notes. private ArrayList notes; /** * Perform any initialization required for the * notebook. */ public Notebook() { notes = new ArrayList (); }... } import java.util.ArrayList; /** *... */ public class Notebook { // Storage for an arbitrary number of notes. private ArrayList notes; /** * Perform any initialization required for the * notebook. */ public Notebook() { notes = new ArrayList (); }... } the type of collection the type of objects in the collection

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Object structures with collections

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Adding a third note

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Features of the collection It increases its capacity as necessary. It keeps a private count ( size() method). It keeps the objects in order. Details of how all this is done are hidden. –Does that matter? Does not knowing how prevent us from using it?

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Using the collection public class Notebook { private ArrayList notes;... public void storeNote(String note) { notes.add(note); } public int numberOfNotes() { return notes.size(); }... } public class Notebook { private ArrayList notes;... public void storeNote(String note) { notes.add(note); } public int numberOfNotes() { return notes.size(); }... } Adding a new note Returning the number of notes (delegation)

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Index numbering

public void showNote(int noteNumber) { if(noteNumber < 0) { // This is not a valid note number. } else if(noteNumber < numberOfNotes()) { System.out.println(notes.get(noteNumber)); } else { // This is not a valid note number. } public void showNote(int noteNumber) { if(noteNumber < 0) { // This is not a valid note number. } else if(noteNumber < numberOfNotes()) { System.out.println(notes.get(noteNumber)); } else { // This is not a valid note number. } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Retrieving an object Index validity checks Retrieve and print the note

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Removal may affect numbering notes.remove(1);

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Removal may affect numbering notes.remove(1);

The ArrayList Class ( java.util.ArrayList) An ArrayList object stores a list of objects, and is often processed using a loop An ArrayList object grows and shrinks as needed, adjusting its capacity as necessary You can reference each object in the list using a numeric index Copyright © 2012 Pearson Education, Inc.

The ArrayList Class Index values of an ArrayList begin at 0 (not 1): 0"Bashful" 1"Sleepy" 2"Happy" 3"Dopey" 4"Doc" Elements can be inserted and removed The indexes of the elements adjust accordingly Copyright © 2012 Pearson Education, Inc.

ArrayList Methods Some ArrayList methods: boolean add (E obj) void add (int index, E obj) Object remove (int index) Object get (int index) boolean isEmpty() int size() Copyright © 2012 Pearson Education, Inc.

The ArrayList Class The type of object stored in the list is established when the ArrayList object is created: ArrayList names = new ArrayList (); ArrayList list = new ArrayList (); This makes use of Java generics, which provide additional type checking at compile time An ArrayList object cannot store primitive types, but that's what wrapper classes are for (Integer, Double, Character, etc.) See Beatles.java Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Beatles.java Author: Lewis/Loftus // // Demonstrates the use of a ArrayList object. //******************************************************************** import java.util.ArrayList; public class Beatles { // // Stores and modifies a list of band members. // public static void main (String[] args) { ArrayList band = new ArrayList (); band.add ("Paul"); band.add ("Pete"); band.add ("John"); band.add ("George"); continue

Copyright © 2012 Pearson Education, Inc. continue System.out.println (band); int location = band.indexOf ("Pete"); band.remove (location); System.out.println (band); System.out.println ("At index 1: " + band.get(1)); band.add (2, "Ringo"); System.out.println ("Size of the band: " + band.size()); for (String name : band) { System.out.println (name); }

Copyright © 2012 Pearson Education, Inc. continue System.out.println (band); int location = band.indexOf ("Pete"); band.remove (location); System.out.println (band); System.out.println ("At index 1: " + band.get(1)); band.add (2, "Ringo"); System.out.println ("Size of the band: " + band.size()); for (String name : band) { System.out.println (name); } Output [Paul, Pete, John, George] [Paul, John, George] At index 1: John Size of the band: 4 Paul John Ringo George

Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: while, do, and for loops Like if statements, if you want to repeat more than one line, you will need to use curly braces ({}) Copyright © 2012 Pearson Education, Inc.

For-each Loops Simplifies repetitive processing of items in a collection For example, suppose bookList is an ArrayList object: ArrayList bookList = new ArrayList (); The following loop will print each book: for (Book myBook : bookList) System.out.println (myBook); Copyright © 2012 Pearson Education, Inc.

Logic of a for-each loop Statements to process each item true false Are there more items in the collection?

Quick Check Copyright © 2012 Pearson Education, Inc. Write a for-each loop that prints all of the Student objects in an ArrayList object called roster. for (Student student : roster) System.out.println (student);

Other Collection Types List (e.g., java.util.ArrayList ) –Ordered elements –Allows duplicates Set (e.g., java.util.HashSet ) –Unordered elements –No duplicates Map (e.g. java.util.HashMap ) –Unordered elements, stored as key-value pairs –No duplicate keys (can be duplicate values) Copyright © 2012 Pearson Education, Inc.

Using collections example Copyright © 2012 Pearson Education, Inc.

Using collections example Copyright © 2012 Pearson Education, Inc.

Using collections example Copyright © 2012 Pearson Education, Inc.

Exercise: iTunes class Create a class Song with –4 Fields: private String title; private String artist; private String album; private double price; –2 Constructors: default, & with a parameter for each field –9 Methods: getters & setters for each field, and toString Create an iTunes class that stores a list of songs as an ArrayList, and initialize the list to be empty –Create a method addSong to the iTunes class Create a main method that adds 3 songs to iTunes (don’t use the default constructor) Copyright © 2012 Pearson Education, Inc.

Group Exercise: iTunes class Create a print method that prints the entire song list using a for each loop Create a getTotalPrice method that returns the total cost of the entire song list Create a getMinimumPrice method that returns the song with the lowest price in the list Copyright © 2012 Pearson Education, Inc.

Homework Finish creating the Song class to prep for next week’s lab Work on Project 1 CodingBat Copyright © 2012 Pearson Education, Inc.