CS 112 Introduction to Programming

Similar documents
Recap: Structure of a Java program CS 112 Introduction to Programming. A Foundation for Programming Why Introduce Static Methods?

Building Java Programs

Topic 3 static Methods and Structured Programming

Building Java Programs

Static Methods & Decomposition

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

Entering the world of Javatar

Building Java Programs

Introduction to Computer Programming

Lecture 1: Basic Java Syntax

Building Java Programs

Building Java Programs Chapter 1

clicker question Comments Using comments Topic 3 static Methods and Structured Programming

CSc 110, Spring Lecture 2: Functions. Adapted from slides by Marty Stepp and Stuart Reges

Building Java Programs Chapter 1

CSE 142, Summer 2015

CSE 142, Summer 2014

CSc 110, Autumn Lecture 2: Functions

Procedural decomposition using static methods

Building Java Programs

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

CSE 201 Java Programming I. Smart Coding School website:

Building Java Programs. Introduction to Java Programming

Recap: Assignment as an Operator CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs. Introduction to Programming and Simple Java Programs

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

A Foundation for Programming

Building Java Programs

CS 112 Introduction to Programming

Building Java Programs

Topic 7 parameters. Based on slides from Marty Stepp and Stuart Reges from

CS 112 Introduction to Programming

Functions (or Static Methods) (Spring 2012)

2.1 Functions. 2.1 Functions. A Foundation for Programming. Functions (Static Methods) x y. f (x, y, z)

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Building Java Programs

2/15/12. CS 112 Introduction to Programming. Lecture #16: Modular Development & Decomposition. Stepwise Refinement. Zhong Shao

CSc 110, Autumn 2016 Lecture 6: Parameters. Adapted from slides by Marty Stepp and Stuart Reges

Lecture 5: Methods CS2301

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

CS 112 Introduction to Programming

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

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

Admin. CS 112 Introduction to Programming. Counting Down: Code Puzzle. Counting Down: Code Puzzle

Getting Started With Java

Building Java Programs

A Unicorn Named Sparkle Word Search. A New Friend for Sparkle Coloring Sheet. A Unicorn Named Sparkle s First Christmas Coloring Sheet

Topic 6 loops, figures, constants

CS 112 Introduction to Programming

The diagram below is only partially complete. Use the terms in the word list to complete the empty boxes. Make dinner

CS 112 Introduction to Programming. (Spring 2012)

Building Java Programs. Chapter 1: Introduction to Java Programming

CS 112 Introduction to Programming. (Spring 2012)

Topic 4 Expressions and variables

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

AP CS Unit 3: Control Structures Notes

Software and Programming 1

2.1 Functions. f (x, y, z)

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Java Programming. What is a program? Programs Recipes. Programs as Recipes 8/16/12. Pancakes In one bowl. mix: 1½ cup flour

Lecture 2: Operations and Data Types

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

1.3 Conditionals and Loops

2.1 Functions. x y. f (x, y, z) A Foundation for Programming. Functions (Static Methods)

CS110D: PROGRAMMING LANGUAGE I

The CS job market. Building Java Programs Chapter 1. Programming languages. What is programming? Introduction to Java Programming

Introduction to Computer Science Unit 2. Notes

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

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

CS 112 Introduction to Programming

Department of Computer Science Yale University Office: 314 Watson Closely related to mathematical induction.

CS 112 Introduction to Programming

CS 112 Introduction to Programming. Final Review. Topic: Static/Instance Methods/Variables: I am confused

CSE 142. Lecture 1 Course Introduction; Basic Java. Portions Copyright 2008 by Pearson Education

Program Development. Program Development. A Foundation for Programming. Program Development

1.3 Conditionals and Loops

Software and Programming 1

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

Chapter 1. Introduction

COMPUTATIONAL THINKING

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS 251 Intermediate Programming Coding Standards

Outline. CIS 110: Introduction to Computer Programming. What is Computer Science? What is computer programming? What is computer science?

CS 112 Introduction to Programming

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

CS 112 Introduction to Programming

CS 112 Introduction to Programming

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CIS 110: Introduction to Computer Programming

Full file at

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Assignment Marking Criteria

Midterms Save the Dates!

Primitive data, expressions, and variables

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

Creating a Program in JCreator. JCreator is then used to create our program. But the first step is to create a new file.

Transcription:

CS 112 Introduction to Programming (Spring 2012) Lecture #6: Static Methods and Decomposition Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements: some slides used in this class are taken directly or adapted from those accompanying the two textbooks: Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne and Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp

Recap: Structure of a Java program A class: - has a name, defined in a file with same name Convention we follow: capitalize each English word - starts with {, and ends with - includes a group of methods public class <class name> { public static void main(string[] args) { <statement>; <statement>;... <statement>; statement: - a command to be executed - end with ; A static method (a.k.a. function ): - has a name Convention we follow: lowercase first word, capital following - starts with {, and ends with - includes a group of statements

A Foundation for Programming any program you might want to write objects static methods & classes build bigger programs and reuse code graphics, sound, and image I/O arrays conditionals and loops Math primitive data types text I/O assignment statements

Why Introduce Static Methods? q Algorithm: A list of steps for solving a problem. q An example algorithm: "Bake two batches of sugar cookies" 1. Preheat oven temperature to 375F. 2. Mix the dry ingredients. 3. Cream the butter and sugar. 4. Beat in the eggs. 5. Stir in the dry ingredients. 6. Set the timer for 8 min. 7. Place 1st batch of cookies to oven. 8. Allow the cookies to bake. 9. Set the timer for 8 min. 10. Place 2nd batch of cookies to oven. 11. Allow the cookies to bake. 12. Mix ingredients for frosting. 13. Spread frosting and sprinkles. Readability of the specification?

Problem of the Specification q Lack of structure: Many tiny steps; tough to remember. A human being typically can only manage seven (plus or minus 2) pieces of information at one time

Problem of the Specification q Redundancy: unnecessary repeat 1. Preheat oven temperature to 375F. 2. Mix the dry ingredients. 3. Cream the butter and sugar. 4. Beat in the eggs. 5. Stir in the dry ingredients. 6. Set the timer for 8 min. 7. Place the first batch of cookies into the oven. 8. Allow the cookies to bake. 9. Set the timer for 8 min. 10. Place the second batch of cookies into the oven. 11. Allow the cookies to bake. 12. Mix ingredients for frosting. 13. Spread frosting and sprinkles.

Structured Algorithms q Structured algorithm: Split into coherent tasks. 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. 3 Bake the cookies. Set the timer for 8 min. Place the cookies into the oven. Allow the cookies to bake. 4 Add frosting and sprinkles. Mix the ingredients for the frosting. Spread frosting and sprinkles onto the cookies.

Structured Algorithms q Structured algorithm provides abstraction (hide/ ignore the right details at the right time) 1 Preheat oven. Set oven to 375 degrees 2 Make the cookie batter. Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. 3 Bake the cookies. Set the timer. Place the cookies into the oven. Allow the cookies to bake. 4 Add frosting and sprinkles. Mix the ingredients for the frosting. Spread frosting and sprinkles onto the cookies.

Removing Redundancy q A well-structured algorithm can describe repeated tasks with less redundancy. 1 Preheat oven. 2 Make the cookie batter. 3a Bake the cookies (first batch). 3b Bake the cookies (second batch). 4 Decorate the cookies.

A Program with Redundancy // This program displays a delicious recipe for baking cookies. public class BakeCookies { public static void main(string[] args) { System.out.println( Preheat the oven."); System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Set the timer."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles."); Issue: How to turn the program into structured specification?

Structured Algorithm? // This program displays a delicious recipe for baking cookies. public class BakeCookies2 { public static void main(string[] args) { // Step 1: preheat oven System.out.println( Preheat oven to 375F."); // Step 2: Make the cookie batter. System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); // Step 3a: Bake cookies (first batch). System.out.println("Set the timer for 8 min."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 3b: Bake cookies (second batch). System.out.println("Set the timer for 8 min."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 4: Decorate the cookies. System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles.");

Static Methods q Arrange statements into groups and give each group a name. q Each such named group of statements is a static method q Writing a static method is like adding a new command to Java. class method A statement statement statement method B statement statement method C statement statement statement

Static Methods q Benefits of methods denote the structure of a program allow code reuse to eliminate redundancy q A main task of programming is procedural decomposition: dividing a problem into methods class method A statement statement statement method B statement statement method C statement statement statement

Gives your method a name so it can be executed q Syntax: public static void <name>() { <statement>; <statement>;... <statement>; q Example: Declaring a Method public static void printwarning() { System.out.println("This product causes cancer"); System.out.println("in lab rats and humans.");

Calling a Method Executes the method's code q Syntax: <name>(); You can call the same method many times if you like. q Example: printwarning(); Output: This product causes cancer in lab rats and humans.

Program with Static Method public class FreshPrince { public static void main(string[] args) { rap(); // Calling (running) the rap method System.out.println(); rap(); // Calling the rap method again // This method prints the lyrics to my favorite song. public static void rap() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); Output: Now this is the story all about how My life got flipped turned upside-down Now this is the story all about how My life got flipped turned upside-down

Design and Use Static Methods 1. Design the algorithm. Look at the structure, look for repeated commands 2. Declare (write down) the methods. Arrange statements into groups and give each group a name. 3. Call (run) the methods. The program's main method executes the other methods to perform the overall task.

Final Cookie Program // This program displays a delicious recipe for baking cookies. public class BakeCookies3 { public static void main(string[] args) { preheatoven(); makebatter(); bake(); // 1st batch bake(); // 2nd batch decorate(); // Step 1: Preheat oven public static void preheatoven() { System.out.println( Preheat Oven to 375F."); // Step 2: Make the cake batter. public static void makebatter() { System.out.println("Mix the dry ingredients."); System.out.println("Cream the butter and sugar."); System.out.println("Beat in the eggs."); System.out.println("Stir in the dry ingredients."); // Step 3: Bake a batch of cookies. public static void bake() { System.out.println("Set the timer for 8 min."); System.out.println("Place a batch of cookies into the oven."); System.out.println("Allow the cookies to bake."); // Step 4: Decorate the cookies. public static void decorate() { System.out.println("Mix ingredients for frosting."); System.out.println("Spread frosting and sprinkles.");

Summary: Why Methods? q Makes code easier to read by capturing the structure of the program main should be a good summary of the program public static void main(string[] args) { public static void main(string[] args) { public static... (...) { Note: Longer code doesn t necessarily mean worse code public static... (...) {

Summary: Why Methods? q Eliminate redundancy public static void main(string[] args) { public static void main(string[] args) { public static... (...) {

Summary: Static Methods Java static methods ( functions ). Takes zero or more input arguments. Returns one output value or none. Side effects (e.g., output to standard draw). more general than mathematical functions Applications. Scientists use mathematical functions to calculate formulas. Programmers use static methods to build modular programs. You use static methods for both. Examples. Built-in functions: Math.random(), Math.abs(), Integer.parseInt(). Our I/O libraries: StdIn.readInt(), StdDraw.line(), StdAudio.play(). User-defined static methods: main().

Anatomy of a Java Static Method Java static methods. Easy to write your own. input output 2.0 f(x) = x 1.414213

More Examples overloading multiple arguments

Method Calling Flow q When a method A calls another method B, the program's execution... "jumps" into method B, executing its statements, then "jumps" back to method A at the point where the method was called.

Methods Calling Methods public class MethodsExample { public static void main(string[] args) { message1(); message2(); System.out.println("Done with main."); public static void message1() { System.out.println("This is message1."); public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); q Output: This is message1. This is message2. This is message1. Done with message2. Done with main.

Methods Calling Methods public class MethodsExample { public static void main(string[] public args) static { void message1() { message1(); System.out.println("This is message1."); message2(); public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with main."); System.out.println("Done with message2.");... public static void message1() { System.out.println("This is message1.");

Summary: Method Control Flow Key point. Static methods provide a new way to control the flow of execution. What happens when a function is called: Control transfers to the function code. Argument variables are assigned the values given in the call. Function code is executed. Return value is assigned in place of the function name in calling code. Control transfers back to the calling code. Note. This is known as "pass by value." 27

When NOT to use methods q You should not create static methods for: Only blank lines. (Put blank printlns in main.) Unrelated or weakly related statements. (A metric of method design is called coherence.)

Static Method Example q Write a program to print these figures using methods. \ / \ / \ / \ / +--------+ STOP \ / \ / +--------+

Development Strategy \ / \ / \ / \ / +--------+ First version (unstructured): Create an empty program and main method. Copy the expected output into it, surrounding each line with System.out.println syntax. Run it to verify the output. STOP \ / \ / +--------+

Program version 1 public class Figures1 { public static void main(string[] args) { System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println("+--------+"); System.out.println(); System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println(" STOP "); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println("+--------+");

Development Strategy 2 \ / \ / \ / \ / +--------+ Second version (structured, with redundancy): Identify the structure of the output. Divide the main method into static methods based on this structure. STOP \ / \ / +--------+

Output Structure \ / \ / \ / \ / +--------+ STOP \ / \ / The structure of the output: initial "egg" figure second "teacup" figure third "stop sign" figure fourth "hat" figure This structure can be represented by methods: egg teacup stopsign hat +--------+

Program version 2 public class Figures2 { public static void main(string[] args) { egg(); teacup(); stopsign(); hat(); public static void egg() { System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); public static void teacup() { System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println("+--------+"); System.out.println();...

Program version 2, cont'd.... public static void stopsign() { System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println(" STOP "); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); public static void hat() { System.out.println(" "); System.out.println(" \"); System.out.println("\"); System.out.println("+--------+");

Development Strategy 3 \ / \ / \ / \ / +--------+ Third version (structured, without redundancy): Identify redundancy in the output, and create methods to eliminate as much as possible. Add comments to the program. STOP \ / \ / +--------+

Output redundancy \ / \ / \ / \ / +--------+ STOP \ / \ / The redundancy in the output: egg top: reused on stop sign, hat egg bottom: reused on teacup, stop sign divider line: used on teacup, hat This redundancy can be fixed by methods: eggtop eggbottom line +--------+

Program version 3 // Suzy Student, CSE 138, Spring 2094 // Prints several figures, with methods for structure and redundancy. public class Figures3 { public static void main(string[] args) { egg(); teacup(); stopsign(); hat(); // Draws the top half of an an egg figure. public static void eggtop() { System.out.println(" "); System.out.println(" \"); System.out.println("\"); // Draws the bottom half of an egg figure. public static void eggbottom() { System.out.println("\\ /"); System.out.println(" \\ /"); // Draws a complete egg figure. public static void egg() { eggtop(); eggbottom(); System.out.println();...

Program version 3, cont'd.... // Draws a teacup figure. public static void teacup() { eggbottom(); line(); System.out.println(); // Draws a stop sign figure. public static void stopsign() { eggtop(); System.out.println(" STOP "); eggbottom(); System.out.println(); // Draws a figure that looks sort of like a hat. public static void hat() { eggtop(); line(); // Draws a line of dashes. public static void line() { System.out.println("+--------+");

A Word about Style q Structure your code properly q Eliminate redundant code q Use spaces judiciously and consistently q Indent properly q Follow the naming conventions q Use comments to describe code behavior

Why Style? q Programmers build on top of other s code all the time. You shouldn t waste time deciphering what a method does. q You should spend time on thinking or coding. You should NOT be wasting time looking for that missing closing brace. q So code with style!