CS 170 Java Programming 1. Week 5: Procedures and Functions

Similar documents
Week 2: Data and Output

CS 170 Java Programming 1. Week 12: Creating Your Own Types

Week 3: Objects, Input and Processing

CS 170 Java Programming 1. Week 9: Learning about Loops

CS 170 Java Programming 1. Week 13: Classes, Testing, Debugging

CS 170 Java Programming 1. Week 10: Loops and Arrays

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

CS 170 Java Programming 1. Week 7: More on Logic

Express Yourself. Writing Your Own Classes

Structured Programming

Instructions PLEASE READ (notice bold and underlined phrases)

Express Yourself. What is Eclipse?

Slide 1 CS 170 Java Programming 1

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 The while Loop Duration: 00:00:60 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Slide 1 CS 170 Java Programming 1 Testing Karel

Spring CS Homework 3 p. 1. CS Homework 3

Express Yourself. The Great Divide

QUIZ Lesson 4. Exercise 4: Write an if statement that assigns the value of x to the variable y if x is in between 1 and 20, otherwise y is unchanged.

CS Homework 11 p. 1. CS Homework 11

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

STUDENT LESSON A1 Introduction to Object-Oriented Programming (OOP)

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

Introduction to Java. Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords

BCIS 3630 Dr. GUYNES SPRING 2018 TUESDAY SECTION [JAN version] GRADER COURSE WEBSITE

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Deadline. Purpose. How to submit. Important notes. CS Homework 9. CS Homework 9 p :59 pm on Friday, April 7, 2017

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

Spring CS Homework 12 p. 1. CS Homework 12

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Chapter 4C Homework Functions III Individual Assignment 30 Points Questions 6 Points Script 24 Points

M.CS201 Programming language

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Com S 127 Lab 2. For the first two parts of the lab, start up Wing 101 and use the Python shell window to try everything out.

CS Homework 11 p. 1. CS Homework 11

Lesson 5C MyClass Methods. By John B. Owen All rights reserved 2011, revised 2014

Slide 1 CS 170 Java Programming 1 Real Numbers Duration: 00:00:54 Advance mode: Auto

Inheritance and Interfaces

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Homework 09. Collecting Beepers

Control Flow: Loop Statements

Instructions PLEASE READ (notice bold and underlined phrases)

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

CSE 230 Intermediate Programming in C and C++ Functions

Computer Science II Lecture 1 Introduction and Background

Tips from the experts: How to waste a lot of time on this assignment

Computer Science AP 2017 Summer Assignment Mrs. McFarland

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

Lecture 1. Course Overview Types & Expressions

CISC 1600 Lecture 3.1 Introduction to Processing

QUIZ Friends class Y;

In the first class, you'll learn how to create a simple single-view app, following a 3-step process:

CS Homework 10 p. 1. CS Homework 10

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

Curriculum Map Grade(s): Subject: AP Computer Science

Lesson Share TEACHER'S NOTES LESSON SHARE. ing by Olya Sergeeva. Overview. Preparation. Procedure

QUIZ. What is wrong with this code that uses default arguments?

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Spring CS Homework 6 p. 1. CS Homework 6

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

First Java Program - Output to the Screen

CS Homework 2 p. 1. CS Homework 2

Tips from the experts: How to waste a lot of time on this assignment

CS 051 Homework Laboratory #2

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers Sjaak Smetsers

Tips from the experts: How to waste a lot of time on this assignment

During the first 2 weeks of class, all students in the course will take an in-lab programming exam. This is the Exam in Programming Proficiency.

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

Outline. Turtles. Creating objects. Turtles. Turtles in Java 1/27/2011 TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

ICS 61 Game Systems and Design Introduction to Scratch

CS111: PROGRAMMING LANGUAGE II

To gain experience using GUI components and listeners.

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

CS 61B Discussion Quiz 1. Questions

In this course, you need to use Pearson etext. Go to "Pearson etext and Video Notes".

QUIZ: What value is stored in a after this

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014


Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

CE221 Programming in C++ Part 1 Introduction

Course: Honors AP Computer Science Instructor: Mr. Jason A. Townsend

CS Fall Homework 11 p. 1. CS Homework 11

Lab 1: Introduction to Java

Recommended Group Brainstorm (NO computers during this time)

CIS 110: Introduction to Computer Programming. Lecture 2 Decomposition and Static Methods ( 1.4)

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

CSCI 200 Lab 3 Using and implementing sets

Instructions. Quiz #2. Name: Solutions Student Number: Signature:

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

Transcription:

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