CS 106A, Lecture 7 Parameters and Return

Slides:



Advertisements
Similar presentations
Overloading Having more than one method with the same name is known as overloading. Overloading is legal in Java as long as each version takes different.
Advertisements

Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
BUILDING JAVA PROGRAMS CHAPTER 3 PARAMETERS AND OBJECTS.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Loops – While, Do, For Repetition Statements Introduction to Arrays
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Copyright 2008 by Pearson Education 1 Class constants and scope reading: 2.4 self-check: 28 exercises: 11 videos: Ch. 2 #5.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 7: User-Defined Methods
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Building Java Programs Parameters and Objects. 2 Redundant recipes Recipe for baking 20 cookies: –Mix the following ingredients in a bowl: 4 cups flour.
Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
February ,  2/16: Exam 1 Makeup Papers Available  2/20: Exam 2 Review Sheet Available in Lecture  2/27: Lab 2 due by 11:59:59pm  3/2:
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
In the last lesson we discussed about: Casting Precedence The “=“ used as an assignment operator Made a calculate average program.
CS 31 Discussion, Week 5 Faisal Alquaddoomi, Office Hours: BH 2432, MW 4:30-6:30pm, F 12:00-1:00pm (today)
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Review Expressions and operators Iteration – while-loop – for-loop.
Test Review. General Info. All tests will be comprehensive. You will be tested more on your understanding of code as opposed to your ability to write.
Copyright 2010 by Pearson Education Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1.
Copyright 2009 by Pearson Education Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1 self-check: #1-6 exercises: #1-3 videos: Ch.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Lecture 7 Methods (functions and subroutines) Parameter Passing
Calling Methods turnRight(); move(); readInt(“Int please! ”);
CS 106A, Lecture 4 Introduction to Java
Building Java Programs Chapter 3
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Suppose we want to print out the word MISSISSIPPI in big letters.
Building Java Programs
Suppose we want to print out the word MISSISSIPPI in big letters.
Building Java Programs
Lecture 07 More Repetition Richard Gesick.
CS106A, Stanford University
Building Java Programs
CS 106A, Lecture 6 Control Flow and Parameters
CS106A, Stanford University
Methods.
CS 106A, Lecture 5 Booleans, Control Flow and Scope
Outline Altering flow of control Boolean expressions
Group Status Project Status.
CS106A, Stanford University
Topic 7 parameters "We're flooding people with information. We need to feed it through a processor. A human must turn information into intelligence or.
Building Java Programs
Redundant recipes Recipe for baking 20 cookies:
Building Java Programs
Building Java Programs
Building Java Programs
SSEA Computer Science: Track A
Chapter 2 Programming Basics.
CSE 142 Lecture Notes Global Constants, Parameters, Return Values
February , 2009 CSE 113 B.
Suggested self-checks: Section 7.11 #1-11
IPC144 Introduction to Programming Using C Week 4 – Lesson 2
Building Java Programs
Building Java Programs
Building Java Programs
Corresponds with Chapter 5
Presentation transcript:

CS 106A, Lecture 7 Parameters and Return suggested reading: Java Ch. 5.1-5.4

Plan For Today Announcements Recap: For Loops Recap: Scope Parameters Return

Plan For Today Announcements Recap: For Loops Recap: Scope Parameters Return

For Loops in Java Repeats the loop if this condition passes This code is run each time the code gets to the end of the ‘body’ This code is run once, just before the for loop starts for (int i = 0; i < 3; i++) { println("I love CS 106A!"); }

Nested loops nested loop: A loop placed inside another loop. Output: for (int i = 0; i < 5; i++) { for (int j = 0; j < 10; j++) { print("*"); } println(); // to end the line Output: ********** The outer loop repeats 5 times; the inner one 10 times. Let’s put these together – nested loops + using the I variable

Nested loop question 2 How would we produce the following output? ....1 ...22 ..333 .4444 55555 Answer: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5 – i - 1; j++) { print("."); } for (int j = 0; j <= i; j++) { print(i + 1); println();

Methods in Java We can define new methods in Java just like in Karel: private void name() { statement; ... } For example: Use to factor out duplicated code private void printGreeting() { println("Hello world!"); println("I hope you have a great day."); }

Methods in Java public void run() { int x = 2; printX(); } private void printX() { // ERROR! "Undefined variable x" println("X has the value " + x); But….methods can’t share variables! Why? SCOPE

Plan For Today Announcements Recap: For Loops Recap: Scope Parameters Return

By Chris Piech

Variable Scope The scope of a variable refers to the section of code where a variable can be accessed. Scope starts where the variable is declared. Scope ends at the termination of the code block in which the variable was declared. A code block is a chunk of code between { } brackets Applies to methods and control flow

Variable Scope You cannot have two variables with the same name in the same scope. for (int i = 1; i <= 100 * line; i++) { int i = 2; // ERROR print("/"); }

Variable Scope You cannot have two variables with the same name in the same scope. for (int i = 1; i <= 100 * line; i++) { int i = 2; // ERROR while (...) { int i = 5; // ERROR } Think: is “i” alive here? Yes!

Variable Scope You can have two variables with the same name in separate scopes. public void run() { for (int i = 0; i < 5; i++) { // i ok here int w = 2; // w ok here } for (int i = 0; i < 2; i++) { // i ok here int w = 3; // w ok here

Variable Scope You can have two variables with the same name in separate scopes. public void run() { int num = 5; cow(); println(num); // prints 5 } private void cow() { int num = 10; println(num); // prints 10

Variable Scope You can have two variables with the same name in different scopes. public void run() { int num = 5; cow(); println(num); } private void cow() { int num = 10; run num 5

Variable Scope You can have two variables with the same name in different scopes. public void run() { int num = 5; cow(); println(num); } private void cow() { int num = 10; run num cow 5

Variable Scope You can have two variables with the same name in different scopes. public void run() { int num = 5; cow(); println(num); } private void cow() { int num = 10; run num cow num 5 10

Variable Scope You can have two variables with the same name in different scopes. public void run() { int num = 5; cow(); println(num); } private void cow() { int num = 10; run num cow num 5 10

Variable Scope You can have two variables with the same name in different scopes. public void run() { int num = 5; cow(); println(num); } private void cow() { int num = 10; run num 5

Plan For Today Announcements Recap: For Loops Recap: Scope Parameters Return

Parameters Parameters let you provide a method some information when you are calling it. Calling just means executing it

Methods = Toasters parameter

readInt(”Your guess? "); Example: readInt readInt(”Your guess? ");

readInt(”Your guess? "); Example: readInt readInt(”Your guess? "); We call readInt We give readInt some information in parenthesis (the text to print to the user)

Example: printGreeting How do we define a command, or method, like this? Finally time to learn about what is inside parentheses… (Prints a greeting a certain number of times)

printGreeting(5); Wouldn’t it be nice if… We give printGreeting some information (the number of greetings to print) We call printGreeting printGreeting(5);

Methods with Parameters Tells Java this method needs one int in order to execute. private void printGreeting(int times) { // use ‘times’ to print the greeting }

Methods with Parameters printGreeting(5); private void printGreeting(int times) { // use ‘times’ to print the greeting }

Methods with Parameters printGreeting(5); private void printGreeting(int times) { for (int i = 0; i < times; i++) { println("Hello world!"); } Copies the value in parenthesis into that variable box

Methods with Parameters public void run() { int repeats = 5; printGreeting(repeats); } private void printGreeting(int times) { for (int i = 0; i < times; i++) { println("Hello world!"); This is the same! Repeats and times have the same value, but are separate variables Copies the value into the new box

Methods with Parameters public void run() { int repeats = 5; printGreeting(repeats); } private void printGreeting(int times) { for (int i = 0; i < times; i++) { println("Hello world!"); This is the same! Repeats and times have the same value, but are separate variables Copies the value into the new box printGreeting times run repeats 5 ?

Methods with Parameters public void run() { int repeats = 5; printGreeting(repeats); } private void printGreeting(int times) { for (int i = 0; i < times; i++) { println("Hello world!"); This is the same! Repeats and times have the same value, but are separate variables Copies the value into the new box printGreeting times run repeats 5 5

Methods with Parameters public void run() { int times = 5; printGreeting(times); } private void printGreeting(int times) { for (int i = 0; i < times; i++) { println("Hello world!"); This is the same! have the same NAME and value, but are separate variables Copies the value into the new box printGreeting times run times 5 ?

Methods with Parameters public void run() { int times = 5; printGreeting(times); } private void printGreeting(int times) { for (int i = 0; i < times; i++) { println("Hello world!"); This is the same! have the same NAME and value, but are separate variables Copies the value into the new box printGreeting times run times 5 5

Parameters are Copies // NOTE: This program is buggy!! public void run() { int x = 3; addFive(x); // prints "x = 3"! println("x = " + x); } private void addFive(int x) { x += 5; run x 3

Parameters are Copies // NOTE: This program is buggy!! public void run() { int x = 3; addFive(x); // prints "x = 3"! println("x = " + x); } private void addFive(int x) { x += 5; run x addFive x 3 3

Parameters are Copies // NOTE: This program is buggy!! public void run() { int x = 3; addFive(x); // prints "x = 3"! println("x = " + x); } private void addFive(int x) { x += 5; run x addFive x 3 8

Parameters are Copies // NOTE: This program is buggy!! public void run() { int x = 3; addFive(x); // prints "x = 3"! println("x = " + x); } private void addFive(int x) { x += 5; run x 3

Parameters parameter: A value passed to a method by its caller. Write a method drawBox to draw a box of any size. When declaring the method, we will state that it requires the caller to tell it the width and height of the box. When calling the method, we will specify the width and height to use. ********** * * 10, 4 run drawBox 7, 5 drawBox ******* * *

Stating that a method requires a parameter in order to run Declaring a parameter Stating that a method requires a parameter in order to run private void name(type name) { statements; } Example: private void password(int code) { println("The password is: " + code); When password is called, the caller must specify the integer code to print.

Multiple parameters A method can accept multiple parameters separated by commas: , When calling it, you must pass values for each parameter. Declaration: private void name(type name, ..., type name) { statements; } Call: name(value, value, ..., value);

Calling a method and specifying values for its parameters Passing a parameter Calling a method and specifying values for its parameters methodName(expression); Example: public void run() { password(42); password(12345); } Output: The password is 42 The password is 12345 Illegal to call without passing an int for that parameter. password(); // Error password(3.7); // Error

How params are passed When the method is called: 7 The value is stored into the parameter variable. The method's code executes using that value. public void run() { chant(7); } private void chant(int times) { for (int i = 0; i < times; i++) { println("Java is great!"); 7

Drawing boxes Lets write a program that uses methods and parameters to print the following boxes: ********** * * ******* * * The code to draw each box will be very similar. Would variables help? Would constants help? What command would be nice to have?

drawBox drawBox(10, 4);

We give drawBox some information (the size of the box we want) We call drawBox drawBox(10, 4);

drawBox private void drawBox(int width, int height) { // use width and height variables // to draw a box }

drawBox ********** * * private void drawBox(int width, int height) { line(width); for (int line = 0; line < height - 2; line++) { boxSide(width); } line(width);

drawBox ********** * * private void drawBox(int width, int height) { line(width); for (int line = 0; line < height - 2; line++) { boxSide(width); } line(width);

drawBox ********** * * private void drawBox(int width, int height) { line(width); for (int line = 0; line < height - 2; line++) { boxSide(width); } line(width);

drawBox ********** * * private void drawBox(int width, int height) { line(width); for (int line = 0; line < height - 2; line++) { boxSide(width); } line(width);

drawBox ********** * * private void drawBox(int width, int height) { line(width); for (int line = 0; line < height - 2; line++) { boxSide(width); } line(width);

line ********** private void line(int count) { for (int i = 0; i < count; i++) { print("*"); } println();

boxSide * * private void boxSide(int width) { print("*"); * * private void boxSide(int width) { print("*"); for (int i = 0; i < width - 2; i++) { print(" "); } println("*");

boxSide ********** * * ******* * * public void run() { drawBox(10, 4); * * ******* * * public void run() { drawBox(10, 4); drawBox(7, 6); }

Plan For Today Announcements Recap: For Loops Recap: Scope Parameters Return

Return Return values let you give back some information when a method is finished. When a method finishes it “returns” back to the caller

Methods = Toasters parameter

Methods = Toasters parameter

Methods = Toasters

Methods = Toasters

Methods = Toasters return

int x = readInt(”Your guess? "); Example: readInt int x = readInt(”Your guess? ");

Example: readInt int x = readInt(”Your guess? "); We call readInt We give readInt some information (the text to print to the user)

int x = readInt(”Your guess? "); Example: readInt int x = readInt(”Your guess? "); When finished, readInt gives us information back (the user’s number) and we put it in x. When we set a variable equal to a method, this tells Java to save the return value in that variable

int x = readInt(”Your guess? "); Example: readInt int x = readInt(”Your guess? "); When we set a variable equal to a method, this tells Java to save the return value of the method in that variable. When we set a variable equal to a method, this tells Java to save the return value in that variable

Example: metersToCm double cm = metersToCm(5); How do we define a command, or method, like this? Finally time to learn about what is inside parentheses… (Returns the given number of m as cm)

Example: metersToCm double cm = metersToCm(5); We give metersToCm some information (the number of meters) We call metersToCm double cm = metersToCm(5); How do we define a command, or method, like this? Finally time to learn about what is inside parentheses…

double cm = metersToCm(5); Example: metersToCm When metersToCm finishes, it returns the number of cm, and we put that in this variable. double cm = metersToCm(5); How do we define a command, or method, like this? Finally time to learn about what is inside parentheses…

Tells Java this method needs one double in order to execute. Methods and Return Tells Java this method needs one double in order to execute. private double metersToCm(double meters) { ... }

Tells Java that, when this method finishes, it will return a double. Methods and Return Tells Java that, when this method finishes, it will return a double. private double metersToCm(double meters) { ... }

Methods and Return Tells Java that, when this method finishes, it will return a double. (Void meant returns nothing) private double metersToCm(double meters) { return 100 * meters; } Void meant returns nothing!

Methods and Return public void run() { double meters = readDouble("#meters? ”); double cm = metersToCm(meters); println(cm + " centimeters."); } private double metersToCm(double meters) { return 100 * meters;

? Methods and Return public void run() { double meters = readDouble("#meters? ”); double cm = metersToCm(meters); println(cm + " centimeters."); } private double metersToCm(double meters) { return 100 * meters; run meters ?

5 Methods and Return public void run() { double meters = readDouble("#meters? ”); double cm = metersToCm(meters); println(cm + " centimeters."); } private double metersToCm(double meters) { return 100 * meters; run meters 5

5 ? Methods and Return public void run() { double meters = readDouble("#meters? ”); double cm = metersToCm(meters); println(cm + " centimeters."); } private double metersToCm(double meters) { return 100 * meters; run meters metersToCm meters 5 ?

5 5 Methods and Return public void run() { double meters = readDouble("#meters? ”); double cm = metersToCm(meters); println(cm + " centimeters."); } private double metersToCm(double meters) { return 100 * meters; run meters metersToCm meters 5 5

5 5 Methods and Return 500 public void run() { double meters = readDouble("#meters? ”); double cm = metersToCm(meters); println(cm + " centimeters."); } private double metersToCm(double meters) { return 100 * meters; 500 run meters metersToCm meters 5 5

5 5 Methods and Return 500 500 public void run() { double meters = readDouble("#meters? ”); double cm = metersToCm(meters); println(cm + " centimeters."); } private double metersToCm(double meters) { return 100 * meters; 500 If you just call metersToCm but don’t save it, it won’t put the 500 anywhere! run cm meters metersToCm meters 500 5 5

5 Methods and Return 500 public void run() { double meters = readDouble("#meters? ”); double cm = metersToCm(meters); println(cm + " centimeters."); } private double metersToCm(double meters) { return 100 * meters; run cm meters 500 5

Methods and Return public void run() { double meters = readDouble("#meters? ”); println(metersToCm(meters) + "cm."); } private double metersToCm(double meters) { return 100 * meters; Can also use the method directly as a value If a method returns something, you can use it directly in an expression!

Return return: To send out a value as the result of a method. Parameters send information in from the caller to the method. Return values send information out from a method to its caller. A call to the method can be used as part of an expression. Q: Why return? Why not just println the result value? run Math.abs(-42) -42 Math.round(2.71) 2.71 42 3

Methods visibility type nameOfMethod(parameters) { statements } visibility: usually private or public type: type returned by method (e.g., int , double, etc.) Can be void to indicate that nothing is returned parameters: information passed into method

Returning Booleans private boolean isEven(int number) { } Can also use the method directly as a value

Returning Booleans private boolean isEven(int number) { if (number % 2 == 0) { return true; else { return false; } Can also use the method directly as a value

Returning Booleans private boolean isEven(int number) { if (number % 2 == 0) { return true; else { return false; } public void run() { int num = readInt("? "); if (isEven(num)) { println("Even!"); } else { println("Odd!"); Can also use the method directly as a value

Returning Booleans private boolean isEven(int number) { return number % 2 == 0; } Can also use the method directly as a value

Returning Booleans public void run() { for(int i = 1; i <= 100; i++) { if(isDivisibleBy(i, 7)) { println(i); } private void isDivisibleBy(int a, int b) { return a % b == 0; Can also use the method directly as a value

Return Return ends a method’s execution. private int multiplyByTwo(int num) { return num * 2; println("Hello world?"); // not executed! } Want to walk through in depth example

Return Return ends a method’s execution. private int max(int num1, int num2) { if(num1 >= num2) { return num1; } return num2; // here only if num1 < num2 Return ends a method’s execution. Want to walk through in depth example public void run() { println(max(2,3)); }

Revisiting a Bug // NOTE: This program is buggy!! public void run() { int x = 3; addFive(x); // prints "x = 3"! println("x = " + x); } private void addFive(int x) { x += 5;

Fixed! // NOTE: This program is feeling just fine public void run() { int x = 3; x = addFive(x); // prints "x = 5"! println("x = " + x); } private int addFive(int x) { x += 5; return x;

Recap Announcements Recap: For Loops Recap: Scope Parameters Return Next time: Strings (new variable type!)