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: 142 + 158• 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) = x2
– 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 xorforeach 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 even0 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 indexwhile (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 valuewhile (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 indexwhile (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<String> guesses = new ArrayList<String>();Scanner s = new Scanner(System.in);
String guess = s.nextLine(); // get input valuewhile (!guess.equals(“quit”) && !guess.equals(“exit”)){ guesses.add(guess); // add line to array list guess = s.nextLine(); // get input value}
User Input Example:
ArrayList<String> guesses = new ArrayList<String>();Scanner s = new Scanner(System.in);
String guess = s.nextLine(); // get input valuewhile (!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 valuewhile (input != end condition){ statements to be repeated get input value}
Copyright © 2012 Pearson Education, Inc.
File Reading Example:
ArrayList<String> lines = new ArrayList<String>();
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<String> lines = new ArrayList<String>();
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 scannerwhile (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 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.
Homework• Implement methods in YOUR ShoppingCart Project• Work on Project• Read Chapter 6
Copyright © 2012 Pearson Education, Inc.