Download presentation
Presentation is loading. Please wait.
Published byNora Atkins Modified over 9 years ago
1
Writing Methods Using if, loops, and variables to implement algorithms Copyright © 2012 Pearson Education, Inc.
2
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
3
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: 142 + 158 Manual solution: Automatic solution:
4
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
5
Problem Solving Process Created by Emily Hill Series of steps for any Programming Language A specific implementation
6
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
7
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) =
8
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.
9
Loop Templates
10
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
11
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; }
12
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;
13
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)); }
14
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 }
15
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 }
16
What does this do? // Print multiples of 5 through 500. for(int num = 5; num <= 500; num += 5) { System.out.println(num); }
17
Do this: for(int num = -15; num <= 15; num += 2) { System.out.println(num); } // Print odd number between -15 and 15 inclusive
18
Writing Methods See “The Process of Writing a Method” Copyright © 2012 Pearson Education, Inc.
19
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.
20
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 //... }
21
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
22
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.
23
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.
24
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.
25
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
26
Homework Implement methods in YOUR ShoppingCart Project Work on Project Read Chapter 6 Copyright © 2012 Pearson Education, Inc.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.