Writing Methods Using if, loops, and variables to implement algorithms Copyright © 2012 Pearson Education, Inc.

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

Arrays I Savitch Chapter 6.1: Introduction to Arrays.
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.
Grouping Objects Arrays and for loops. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Fixed-Size Collections.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Loops – While, Do, For Repetition Statements Introduction to Arrays
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Operator Overloading in C++
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Expressions, Data Conversion, and Input
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus.
1 CSC 222: Object-Oriented Programming Spring 2012 Object-oriented design  example: word frequencies w/ parallel lists  exception handling  System.out.format.
1 CSC 221: Computer Programming I Spring 2008 ArrayLists and arrays  example: letter frequencies  autoboxing/unboxing  ArrayLists vs. arrays  example:
School of Computer Science & Information Technology G6DICP - Lecture 9 Software Development Techniques.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Patterns with.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
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.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 5: Control Structures II
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
CSCI 6962: Server-side Design and Programming JSF DataTables and Shopping Carts.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
Programming Fundamentals I Java Programming Spring 2009 Instructor: Xuan Tung Hoang TA: Tran Minh Trung Lab 03.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
CSE 1201 Object Oriented Programming ArrayList 1.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
1 b Boolean expressions b truth tables b conditional operator b switch statement b repetition statements: whilewhile do/whiledo/while forfor Lecture 3.
Jeopardy Print Me Which loop? Call Me Name Me My Mistake Q $100 Q $200 Q $300 Q $400 Q $500 Q $100 Q $200 Q $300 Q $400 Q $500 Final Jeopardy.
Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Project 1.
Loop Structures.
Repetition-Counter control Loop
Chapter 5: Control Structures II
CSS161: Fundamentals of Computing
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
ITunes Lab Copyright © 2012 Pearson Education, Inc.
Programming We have seen various examples of programming languages
CSC 222: Object-Oriented Programming Spring 2013
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Building Java Programs
CSC 222: Object-Oriented Programming Spring 2012
Presentation transcript:

Writing Methods Using if, loops, and variables to implement algorithms Copyright © 2012 Pearson Education, Inc.

So what is Computer Science, anyway? Computers are a powerful automation tool, but we need to tell them what to do… –How can we communicate with them to take advantage of this power? –How do we break down our problems so they can be automatically solved by computers? –How can we organize our solutions so that others can take advantage of them? (and so we don’t always need to reinvent the wheel either) Created by Emily Hill

Manual vs Automated Problem Solving Created by Emily Hill Problem: bake cookies –Manual solution: baker bakes in kitchen –Automatic solution: Problem: searching for a phone # –Manual solution: person flips through yellow pages –Automatic solution: Problem: Manual solution: Automatic solution:

Telling computers what to do… Computer programming: implement solutions to solve new problems automatically Types of problems we can solve with a computer? Anything that deals with digital data Algorithm: a set of precise, unambiguous steps that can be used to accomplish some task (i.e., solve a problem) Created by Emily Hill

Problem Solving Process Created by Emily Hill Series of steps for any Programming Language A specific implementation

Problem Solving 101 Fundamental capabilities of any computer or programming language: –store single values x = 5 (variables)hellothere = “howdy” –store lists of values array = 1:5 (collections & arrays)array = 1, 4, 7, 8 –functions(methods) f(x) = x 2 –conditionals if (x == f(x)) then print “x is 0 or 1” else print “x is not 0 or 1” –loops foreach x in (1:5) print x or foreach x in (array) print x 5 principles can combine in infinitely many ways – once mastered, you can create any program ever written! Created by Emily Hill

Give it a try… Problem: sum all the even numbers from 1 to 10 Use the 5 principles on the prior slide to solve Assume the following function is already defined: 1 if x is even 0 otherwise Hint: you may find it helpful to build your solution incrementally: –Step 1: print out the numbers from 1 to 10 –Step 2: print out the even numbers from 1 to 10 –Step 3: sum the even numbers from 1 to 10 Created by Emily Hill isEven(x) =

The Importance of Templates Templates are examples we understand that we can reuse & modify to solve brand new problems Anything can be a template: –Algorithms are problem solving templates –A Square or PiggyBank class can be a template –Getters & setters can be templates –Print methods or loops can be templates During class, I often give you examples that can serve as templates for assignments or lab exercises (think ITunes → ShoppingCart) But what if you can’t find a template for the method you’re trying to write? See “The Process of Writing a Method” Copyright © 2012 Pearson Education, Inc.

Loop Templates

Review: Loop Templates Copyright © 2012 Pearson Education, Inc. While Loop Index Template: initialize index while (condition){ statements to be repeated update index } For Loop Template: for (initialize index; condition; update index){ statements to be repeated } For Each Loop Template: for (ElementType elementName : collection){ statements to be repeated } While Loop Sentinel Template: get input value while (input != end condition){ statements to be repeated get input value } Counting examples: print all the even numbers from 2 up to 1000 ITunes examples: print all songs in an array list songs Counting examples: print all the even numbers from 2 up to 1000 ITunes examples: print all songs in an array list songs

Copyright © 2012 Pearson Education, Inc. ITunes Example: int i = 0; while (i < songs.size()){ System.out.println(songs.get(i)); i++; } ITunes Example: int i = 0; while (i < songs.size()){ System.out.println(songs.get(i)); i++; } While Loop Index Template: initialize index while (condition){ statements to be repeated update index } Counting Example: int i = 2; while (i < 1000){ System.out.println(i); i = i + 2; } Counting Example: int i = 2; while (i < 1000){ System.out.println(i); i = i + 2; }

Copyright © 2012 Pearson Education, Inc. ITunes Example: for (int i = 0; i < songs.size(); i++){ System.out.println(songs.get(i)); } ITunes Example: for (int i = 0; i < songs.size(); i++){ System.out.println(songs.get(i)); } For Loop Index Template: for (initialize index; condition; update index){ statements to be repeated } Counting Example: for (int i = 2; i < 1000; i += 2) { System.out.println(i); } Counting Example: for (int i = 2; i < 1000; i += 2) { System.out.println(i); } All the following are equivalent: i = i + 1; i++; i += 1; All the following are equivalent: i = i + 1; i++; i += 1;

Copyright © 2012 Pearson Education, Inc. ITunes For Each Loop Example: for (Song s : songs){ System.out.println(s); } ITunes For Each Loop Example: for (Song s : songs){ System.out.println(s); } For Each Loop Template: for (ElementType elementName : collection){ statements to be repeated } ITunes For Loop Index Example: for (int i = 0; i < songs.size(); i++){ System.out.println(songs.get(i)); } ITunes For Loop Index Example: for (int i = 0; i < songs.size(); i++){ System.out.println(songs.get(i)); }

Copyright © 2012 Pearson Education, Inc. User Input Example: ArrayList guesses = new ArrayList (); Scanner s = new Scanner(System.in); String guess = s.nextLine(); // get input value while (!guess.equals(“quit”) && !guess.equals(“exit”)){ guesses.add(guess); // add line to array list guess = s.nextLine(); // get input value } User Input Example: ArrayList guesses = new ArrayList (); Scanner s = new Scanner(System.in); String guess = s.nextLine(); // get input value while (!guess.equals(“quit”) && !guess.equals(“exit”)){ guesses.add(guess); // add line to array list guess = s.nextLine(); // get input value } While Loop Sentinel Template (User Input): get input value while (input != end condition){ statements to be repeated get input value }

Copyright © 2012 Pearson Education, Inc. File Reading Example: ArrayList lines = new ArrayList (); Scanner s = new Scanner(new File(“in.txt”)); while (s.hasNext()){ String line = s.nextLine(); // get input System.out.println(line); // print line lines.add(line); // add line to array list } File Reading Example: ArrayList lines = new ArrayList (); Scanner s = new Scanner(new File(“in.txt”)); while (s.hasNext()){ String line = s.nextLine(); // get input System.out.println(line); // print line lines.add(line); // add line to array list } While Loop Sentinel Template (File Input): setup file scanner while (there is more input){ get input statements to be repeated }

What does this do? // Print multiples of 5 through 500. for(int num = 5; num <= 500; num += 5) { System.out.println(num); }

Do this: for(int num = -15; num <= 15; num += 2) { System.out.println(num); } // Print odd number between -15 and 15 inclusive

Writing Methods See “The Process of Writing a Method” Copyright © 2012 Pearson Education, Inc.

Shopping Cart Part B: Create a Shopping Cart Create a new class, ShoppingCart, with a single field, items, that can hold any number of items (Hint: you should be using an ArrayList) Create a default constructor that creates an empty cart Create the following methods. After you write each method, test it by running main. –insertItem which adds an Item to the end of the cart (use only 1 parameter) –print which prints the name and price of each item on a separate line using a loop –removeItem which removes an item at a given index Copyright © 2012 Pearson Education, Inc.

Remember Shopping Cart? Copyright © 2012 Pearson Education, Inc. public class Item { private String name, description; private double price; // constructors // getter & setter methods: // getName(), getPrice(), getDescription(), etc. // toString & printDeails } public class Item { private String name, description; private double price; // constructors // getter & setter methods: // getName(), getPrice(), getDescription(), etc. // toString & printDeails } public class ShoppingCart { ArrayList items= new ArrayList (); // print, insertItem, removeItem //... } public class ShoppingCart { ArrayList items= new ArrayList (); // print, insertItem, removeItem //... }

Shopping Cart Part A: Define a shopping cart item Create a new project, ShoppingCart Create a new class, Item, that has 3 fields: name, price, and description Create a constructor that takes a parameter for each field, as well as a default constructor that initializes the fields to default values (e.g., “” for a string, ‘ ’ for a char, or 0 for a number) Create getter and setter methods for each field (try using Source > Generate Getters and Setters) Create a printDetails method that prints the details of the item on a single line. Create a toString method that returns the item’s name and price as a String

Shopping Cart Part B: Create a Shopping Cart Create a new class, ShoppingCart, with a single field, items, that can hold any number of items (Hint: you should be using an ArrayList) Create a default constructor that creates an empty cart Create the following methods. After you write each method, test it by running main. –insertItem which adds an Item to the end of the cart (use only 1 parameter) –print which prints the name and price of each item on a separate line using a loop –removeItem which removes an item at a given index Copyright © 2012 Pearson Education, Inc.

Shopping Cart Part B: Create a Shopping Cart Create the following methods. After you write each method, test it by running in main. –getTotal which returns the total price of all items in the cart using a loop –insertUniqueItem which adds an item only if no other items in the shopping cart have the same name –getMaximumPricedItem which returns the most expensive item in the cart –printInvoice which prints the details of each item on a separate line using a loop, followed by the total 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.

More Practice: Timer class Create a Timer class that counts down from n to 0 (where n is specified by the constructor, 5 by default for the default constructor) You will need 2 fields: n & time_left Write a tick method that decrements the time left if time left is greater than zero, otherwise it prints: “You have no time left!” Created by Emily Hill & Jerry Alan Fails

Homework Implement methods in YOUR ShoppingCart Project Work on Project Read Chapter 6 Copyright © 2012 Pearson Education, Inc.