CS 170 Java Programming 1 Week 5: Procedures and Functions
What s the Plan? Topic 1: More on graphical objects Creating your own custom Turtle types Introducing media, pictures and sounds Topic 2: Decomposition: writing your own procedures Learn to eliminate redundancy Topic 3: Passing Parameters Learn how to define formal parameters Topic 4: Writing functions Learn to write and test your own user-defined functions
Your "IC" or "Lab" Document Use Word or OpenOffice to create a new document Save the file as IC05.doc (Office 97-2003 compatible) Place on your network U: drive or on a thumb drive Put your name and today's date at the top of the sheet Title it "CS 170 Lab Exercises Week 5" Start DrJava and we'll do a little bit with Turtles Exercise 5.1: Create and display a Turtle named sam Shoot a screen-shot and paste it into your IC document
Drawing a Square Exercise 5.2: ask sam to draw a square; the algorithm: Ask sam to turn right Ask sam to go forward 50 units Ask sam to turn right again Ask sam to go forward 50 more units Ask sam to turn right again Ask sam to go forward 50 more units Ask sam to turn right one last time Ask sam to go forward one final 50 units Snap a picture when finished.
Your Very Own Turtle Type Much easier if we could just tell sam to draw a square Turtle class doesn't have any drawsquare() method Solution? Create our own smarter Turtle class This is known as Inheritance Lets us create new types by building on existing types Exercise 5.2: Create a new file in Definitions Pane Create a class named MyTurtle Add phrase extendsbasicturtle to header Create a new MyTurtle object named yertle
Adding a drawsquare Method The syntax for a new "turtle command" looks like this: public void drawsquare() { // put the instructions here } Place this inside the MyTurtle class So, what do we put for the "instructions"? yertle.turnleft() doesn't work We don't have a MyTurtle object Inside class, current active object is named this
The drawsquare Instructions Exercise 5.3: Add the drawsquare() method Create a new MyTurtle object and have it draw this Snap a screen-shot and paste it into your IC document
A Bigger Square? Improve drawsquare() by using a variable public void drawsquare() { int width = 50; this.turnright(); this.forward(width); //.. and so on } Better because we only have to change one line MyTurtle still only draws one size square
Adding a Parameter Move variable declaration to parameter list public void drawsquare(int width) { this.turnright(); this.forward(width); //.. and so on } You supply the size when you ask your turtle to draw Means that your turtle can draw any size square Parameters make methods more flexible
Try It Yourself Exercise 5.4: complete improved drawsquare() Start by typing this into the Interactions Pane MyTurtle tom = new MyTurtle(); tom.forward(50); tom.drawsquare(30); tom.turn(30); tom.drawsquare(50); Add commands until your picture looks like this Snap a pic.
Topic 2 Programs and Procedures Adding Procedures to Eliminate Redundancy (Gaddis 4.1)
Introducing Procedures Exercise 5.5: open Abacus.java in your Week 5 folder Single main that draws an Abacus on screen Snap a picture Now, copy file by using Save As Abacus2.java Make sure you rename class after saving Both class and file must have the same name Want to learn how to use multiple procedures "Procedures" are methods that "carry out an action" First task is learning the syntax
Procedures Procedures let us divide a complex tasks into simpler pieces by decomposing the complex task To define a simple procedure you write this: public static void onestep() { // actions needed for one step } Almost like drawsquare(), except for static keyword Needed when a procedure is called from main()
Defining printtophalf Exercise 5.6: create a procedure printtophalf() Make sure it appears inside the Abacus2 class Cut the statements out of the main() method that draw the top half of the abacus. Paste them into the body of the printtophalf() method. Compile, run and snap a screen-shot.
Calling Procedures Your abacus is missing the top half. Why? Because you defined the procedure but didn't call it To call a procedure you type its name and a semicolon: printtophalf(); Place at the point where you want this performed Exercise 5.6: call the printtophalf() method from the main() method. Compile, run and snap a picture.
Completing Abacus2 Exercise 5.7: Do the printbottomhalf() procedure on your own. Run and shoot a screenshot. Procedures can be used for more than just printing values or returning information about an object. Provide a powerful way to solve problems Put multiple steps into a single, simple method Use simple method as a building block for larger methods Procedural decomposition or divide and conquer
Introducing Decomposition Decomposition allows us to complete more complex jobs in a simpler way, eliminating redundancy
Applying Decomposition Early on, the easiest way to apply decomposition is to first write the redundant code first and then add procedures Largest procedures first Notice the patterns Then divide into smaller procedures As you gain more experience, you'll often work the other way around (called bottom up design) Good programmers alternate between these Open Abacus, save as Abacus3, rename class
Locate Redundant Code Look at the redundant or repeated lines in code
Stepwise Refinement Exercise 5.8: define a printbeads() procedure Copy code to print one line of beads Call printbeads() from main() method Now we still have redundant calls to printbeads() Replace two calls to printbeads() with a printtwobeads() method (calls printbeads()) Again? Add a printfourbeads() method that calls printtwobeads() Compile and run. Shoot a screen-shot of your code
Abacus3
Topic 3 Writing Functions with Parameters Writing Functions to Calculate Values (Gaddis 4.2-4.4)
Writing Functions We are going to start moving away from IPO programs and start moving towards writing functions Think of these as "mini" IPO programs Here are the major differences: No user input. Input comes only through the parameter list No visible output: output is returned from the function Can still have a main() method with regular input and output to test the function; you won't do I/O in the function Let's start with a String function
The helloname Example Given a Stringname, e.g. "Bob", return a greeting of the form "Hello Bob!". helloname("bob") "Hello Bob!" helloname("alice") "Hello Alice!" helloname("x") "Hello X!" First, let's write this as an IPO program HelloName.java Create a String variable, read the user's name Print the result by using concatenation Now, open StringFunctions.java
Function Syntax Functions (value-producing methods) are procedures: That have a return type other than void And end with a return expression This is the function output: public static rettype funcname(args) { // statements return rettype-expression; }
Let's Create a Function Write the a "first-draft" skeleton for the helloname() function by asking these questions: 1. What is the access? (always use public) 2. What kind of thing does the function return? 3. What is the name of the function? 4. Skip parameters for now. Just put in () 5. Add braces to surround the function body. 5. Create a variable for the result, and initialize 6. Return the result Now, let's look at the input
Function Inputs Instead of reading input, a function uses parameters A formal parameter variable is a local variable that: is declared inside the argument list is given a value when the function is called helloname() with a formal parameter (or argument) public static String helloname(string name) { return result; }
Testing Your Function Informally test by using the Interactions Pane Run test suit by using CheckResults Compares expected to actual output
Completing helloname Exercise 5.9: complete the method by using concatenation to combine the inputs with the desired greeting. Run tests and shoot a screen shot.
Introducing JavaBat Site developed by Prof. Nick Parlante at Stanford Can use instead of DrJava for functions exercises Go to http://www.javabat.com May create account if you want to save your work
A JavaBat Example Locate the makeabba problem in String1 section String problems that don't require loops this week
Solving the Problem On proficiency quizzes, you'll write skeleton yourself Always start by completing the supplied skeleton 1. Create a variable, same type as return type I usually name it result Initialize it to an "empty" value (0, 0.0, false, or "") 2. Add the return expression with result 3. Run the program Check the expected output, then write code to fix Exercise 5.10: complete problem and shoot a screen-shot
Finishing Up To complete your IC "lab" document: Complete Exercise 5.11 in the Writing Procedures lesson, Exercise 5.12 in the Passing Parameters lesson, Exercise 5.13 in the Writing Functions lesson, Exercises 5.14-15 in the Syntax Errors lesson and Exercise 5.16 in the Style Rules lesson. Submit to Blackboard when done Reading for next week: Gaddis: read Chapter 4, MediaComp: Chapter 3
Homework and Quiz Homework, Quiz and Assignments Deadline is Monday at noon Eight homework problems (1 extra-credit) 2 procedures and using String functions 5 small String function problems Upload to Assignment Dropbox. Make sure to press Submit Proficiency Quiz 4: Simple String functions Practice on assignments You will have ½ hour, assigned seating