0% found this document useful (0 votes)
5 views94 pages

Lecture 7

The document outlines the content of CS 106A Lecture 7, focusing on parameters and return values in Java. It includes discussions on for loops, variable scope, and how to define methods with parameters. Additionally, it explains how parameters are passed and how return values can provide information back to the caller.

Uploaded by

rajeshsv.ignou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views94 pages

Lecture 7

The document outlines the content of CS 106A Lecture 7, focusing on parameters and return values in Java. It includes discussions on for loops, variable scope, and how to define methods with parameters. Additionally, it explains how parameters are passed and how return values can provide information back to the caller.

Uploaded by

rajeshsv.ignou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS 106A, Lecture 7

Parameters and Return

suggested reading:
Java Ch. 5.1-5.4

This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others.
Plan For Today
•Announcements
•Recap: For Loops
•Recap: Scope
•Parameters
•Return

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

3
For Loops in Java
Repeats the loop
if this condition
passes

for (int i = 0; i < 3; i++) {


println("I love CS 106A!");
}

4
Nested loops
• nested loop: A loop placed inside another loop.
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. 5


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();
}
6
Methods in Java
We can define new methods in Java just like in Karel:

private void name() {


statement;
statement;
...
}
For example:
private void printGreeting() {
println("Hello world!");
println("I hope you have a great day.");
}
7
Methods in Java
public void run() {
int x = 2;
printX();
}

private void printX() {


// ERROR! "Undefined variable x"
println("X has the value " + x);
}

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

9
By Chris Piech
10
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
11
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("/");
}

12
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
}
}

13
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
}
}
14
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
}
15
Variable Scope
You can have two variables with the same
name in different scopes.

public void run() { run


int num = 5;
cow();
5
println(num); num
}

private void cow() {


int num = 10;
println(num);
}
16
Variable Scope
You can have two variables with the same
name in different scopes.

public void run() { run


int num = 5;
cow();
cow
5
println(num); num
}

private void cow() {


int num = 10;
println(num);
}
17
Variable Scope
You can have two variables with the same
name in different scopes.

public void run() { run


int num = 5;
cow();
cow
510
println(num); num
num
}

private void cow() {


int num = 10;
println(num);
}
18
Variable Scope
You can have two variables with the same
name in different scopes.

public void run() { run


int num = 5;
cow();
cow
510
println(num); num
num
}

private void cow() {


int num = 10;
println(num);
}
19
Variable Scope
You can have two variables with the same
name in different scopes.

public void run() { run


int num = 5;
cow();
5
println(num); num
}

private void cow() {


int num = 10;
println(num);
}
20
Plan For Today
•Announcements
•Recap: For Loops
•Recap: Scope
•Parameters
•Return

21
Parameters

Parameters let you provide a


method some information
when you are calling it.

22
Methods = Toasters

parameter

23
Example: readInt

readInt(”Your guess? ");

24
Example: readInt

We call We give readInt some


readInt information in parenthesis
(the text to print to the user)

readInt(”Your guess? ");

25
Example: printGreeting

printGreeting(5);

(Prints a greeting a certain number of times)

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

printGreeting(5);

27
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
}

28
Methods with Parameters

printGreeting(5);

private void printGreeting(int times) {


// use ‘times’ to print the greeting
}
29
Methods with Parameters

printGreeting(5);

private void printGreeting(int times) {


for (int i = 0; i < times; i++) {
println("Hello world!");
}
}

30
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!");
}
}

31
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!");
}
} printGreeting
run

5 ?
repeats times
32
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!");
}
} printGreeting
run

5 5
repeats times
33
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!");
}
} printGreeting
run

5 ?
times times
34
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!");
}
} printGreeting
run

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

private void addFive(int x) {


x += 5;
}

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

private void addFive(int x) {


x += 5;
}

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

private void addFive(int x) {


x += 5;
}

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

private void addFive(int x) {


x += 5;
}

39
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 *******
* *
* *
* *
*******
40
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.

41
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);

42
Passing a parameter
Calling a method and specifying values for its parameters

methodName(expression);

• Example:
public void run() {
password(42);
password(12345);
} • Illegal to call without passing an
int for that parameter.
Output:
The password is 42 password(); // Error
The password is 12345 password(3.7); // Error

43
How params are passed
• When the method is called:
– The value is stored into the parameter variable.
– The method's code executes using that value.

public void run() {


chant(7);
} 7
private void chant(int times) {
for (int i = 0; i < times; i++) {
println("Java is great!");
}
}

44
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?
45
drawBox

drawBox(10, 4);

46
drawBox
We give drawBox some
We call
information (the size of
drawBox
the box we want)

drawBox(10, 4);

47
drawBox

private void drawBox(int width, int height) {


// use width and height variables
// to draw a box
}

48
drawBox
**********
* *
* *
**********

private void drawBox(int width, int height) {


line(width);
for (int line = 0; line < height - 2; line++) {
boxSide(width);
}
line(width);
}

49
drawBox
**********
* *
* *
**********

private void drawBox(int width, int height) {


line(width);
for (int line = 0; line < height - 2; line++) {
boxSide(width);
}
line(width);
}

50
drawBox
**********
* *
* *
**********

private void drawBox(int width, int height) {


line(width);
for (int line = 0; line < height - 2; line++) {
boxSide(width);
}
line(width);
}

51
drawBox
**********
* *
* *
**********

private void drawBox(int width, int height) {


line(width);
for (int line = 0; line < height - 2; line++) {
boxSide(width);
}
line(width);
}

52
drawBox
**********
* *
* *
**********

private void drawBox(int width, int height) {


line(width);
for (int line = 0; line < height - 2; line++) {
boxSide(width);
}
line(width);
}

53
line

**********

private void line(int count) {


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

54
boxSide

* *

private void boxSide(int width) {


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

55
boxSide

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

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

57
Return

Return values let you give


back some information when
a method is finished.

58
Methods = Toasters

parameter

59
Methods = Toasters

parameter

60
Methods = Toasters

61
Methods = Toasters

62
Methods = Toasters

return

63
Example: readInt

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

64
Example: readInt

We call We give readInt some


readInt information (the text to
print to the user)

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

65
Example: readInt
When finished, readInt gives
us information back (the user’s
number) and we put it in x.

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

66
Example: readInt

When we set a variable equal to a method, this tells Java


to save the return value of the method in that variable.

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

67
Example: metersToCm

double cm = metersToCm(5);

(Returns the given number of m as cm)

68
Example: metersToCm
We give
We call metersToCm some
metersToCm information (the
number of meters)

double cm = metersToCm(5);

69
Example: metersToCm

When metersToCm finishes, it


returns the number of cm, and
we put that in this variable.

double cm = metersToCm(5);

70
Methods and Return
Tells Java this method
needs one double in order
to execute.

private double metersToCm(double meters) {


...
}

71
Methods and Return
Tells Java that, when this
method finishes, it will
return a double.

private double metersToCm(double meters) {


...
}

72
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;
}

73
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;
}

74
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
75
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

5
meters
76
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 metersToCm

5 ?
meters meters
77
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 metersToCm

5 5
meters meters
78
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;
} 500
run metersToCm

5 5
meters meters
79
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;
} 500
run metersToCm
500 5 5
cm meters meters
80
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
500 5
cm meters
81
Methods and Return
public void run() {
double meters = readDouble("#meters? ”);
println(metersToCm(meters) + "cm.");
}

private double metersToCm(double meters) {


return 100 * meters;
}

If a method returns something, you


can use it directly in an expression!
82
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.

-42 Math.abs(-42)

42
run
2.71

3
Math.round(2.71)

– Q: Why return? Why not just println the result value?


83
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
84
Returning Booleans
private boolean isEven(int number) {

85
Returning Booleans
private boolean isEven(int number) {
if (number % 2 == 0) {
return true;
else {
return false;
}
}

86
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!");
}
} 87
Returning Booleans
private boolean isEven(int number) {
return number % 2 == 0;
}

88
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;
}

89
Return
Return ends a method’s execution.

private int multiplyByTwo(int num) {


return num * 2;
println("Hello world?"); // not executed!
}

90
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
}

public void run() {


println(max(2,3));
}
91
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;
}

92
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;
}

93
Recap
•Announcements
•Recap: For Loops
•Recap: Scope
•Parameters
•Return

Next time: Strings (new variable type!)

94

You might also like