Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
Welcome Back!
Welcome to Java!
What is Java?
● Java is an industrial programming language used to build large applications.
● Used in web servers, Android phones, desktop applications, etc.
● Extremely common: probably the second-most-widely used language in professional software engineering.
Transitioning to Java
● For the remainder of Girl Code, we'll be using the Java programming language.
● Java and Alice have many things in common:● Methods● Parameters● Control Statements (while, if, etc.)● Events
● Although the languages look different, you'll see these parallels as we keep going.
Our First Java Program
Running This Program
● Downloading and running programs in Java is different from running them in Alice.
● Don't worry, we'll work through it together!
Step One: Download the Project
Go to http://bit.ly/girlcode andclick on Java Projects.
Step Two: Extract the Files
Double-click the .zip file to extract the folder. Don't click on any of the files just
yet – we'll get there in a second!
Step Three: Move the Files
Copy the directory you extracted somewhere convenient (we recommend the
desktop.)
Step Four: Import the Project
Click on the Import button,which looks like this:
Navigate to the folder Java01and click Finish.
Step Five: Open the Source Files
Navigate in the project to “Default Package” and double-click on the Java
source file AddTwoIntegers.java
Step Six: Run the Program!
Click on the icon of a little running guy. The program should start running!
Dissecting our Program
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
This Java code needs to be in every program we'll write in these next two weeks. Because of this, it's often called boilerplate code.
We'll provide this code for you so
This Java code needs to be in every program we'll write in these next two weeks. Because of this, it's often called boilerplate code.
We'll provide this code for you so that you don't have to type it.
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
This is the name of the program. Since this program
adds two integers, I've named it “AddTwoIntegers
This is the name of the program. Since this program
adds two integers, I've named it “AddTwoIntegers.”
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}} This is the run
method. It's the actual
This is the run method. It's
the actual program to run.
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
Each of these lines of code is called a statement. Each
Each of these lines of code is called a statement. Each
statement ends with a semicolon.
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
The println method (print line) displays a line of text on the
screen. The quoted text in the parentheses is the argument to
The println method (print line) displays a line of text on the
screen. The quoted text in the parentheses is the argument to
the method.
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
These statements are called variable declarations. They allow
us to give names to quantities (here, the first two numbers
These statements are called variable declarations. They allow
us to give names to quantities (here, the first two numbers
entered and their sum).
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}} These are comments, just
like in Alice. (Notice that
These are comments, just like in Alice. (Notice that
they still start with //).
Working with Variables
● The previous program declared three variables: n1, n2, and sum.
● In the previous example, we used these variables to keep track of values that the user entered and to store information for later on.
● Variables are very important in Java, so we'll start with a quick overview of how to use them.
Variables
● A variable is a location where a program can store information for later use.
Variables
● A variable is a location where a program can store information for later use.
Variables
● A variable is a location where a program can store information for later use.
● Each variable has three pieces of information associated with it:
Variables
● A variable is a location where a program can store information for later use.
● Each variable has three pieces of information associated with it:● Name: What is the variable called?
Variables
● A variable is a location where a program can store information for later use.
● Each variable has three pieces of information associated with it:● Name: What is the variable called?● Type: What sorts of things can you store in the
variable?● Value: What value does the variable have at any
particular moment in time?
int numVoters
Variables
● A variable is a location where a program can store information for later use.
● Each variable has three pieces of information associated with it:● Name: What is the variable called?● Type: What sorts of things can you store in the
variable?
int numVoters
Variables
● A variable is a location where a program can store information for later use.
● Each variable has three pieces of information associated with it:● Name: What is the variable called?● Type: What sorts of things can you store in the
variable?● Value: What value does the variable have at any
particular moment in time?
int numVoters
Variables
● A variable is a location where a program can store information for later use.
● Each variable has three pieces of information associated with it:● Name: What is the variable called?● Type: What sorts of things can you store in the
variable?● Value: What value does the variable have at any
particular moment in time?
int numVoters
Variables
● A variable is a location where a program can store information for later use.
● Each variable has three pieces of information associated with it:● Name: What is the variable called?● Type: What sorts of things can you store in the
variable?● Value: What value does the variable have at any
particular moment in time?
137 int numVoters
Variables
A variable is a location where a program can store information for later use.
Each variable has three pieces of information associated with it:● Name: What is the variable called?● Type: What sorts of things can you store in the
variable?● Value: What value does the variable have at any
particular moment in time?
137 int numVoters
Variable Names
● Legal names for variables● begin with a letter or an underscore (_)● consist of letters, numbers, and underscores,
and● aren't one of Java's reserved words.
x w7thBookInTheSeries LOUD_AND_PROUDHarry Potter that'sACoolNamenoOrdinaryRabbit voidlots_of_underscores C_19_H_14_O_5_S
Variable Names
● Legal names for variables● begin with a letter or an underscore (_)● consist of letters, numbers, and underscores,
and● aren't one of Java's reserved words.
x w7thBookInTheSeries LOUD_AND_PROUDHarry Potter that'sACoolNamenoOrdinaryRabbit voidlots_of_underscores C_19_H_14_O_5_S
Variable Names
● Legal names for variables● begin with a letter or an underscore (_)● consist of letters, numbers, and underscores,
and● aren't one of Java's reserved words.
x w7thBookInTheSeries LOUD_AND_PROUDHarry Potter that'sACoolNamenoOrdinaryRabbit voidlots_of_underscores C_19_H_14_O_5_S
Variable Names
● Legal names for variables● begin with a letter or an underscore (_)● consist of letters, numbers, and underscores,
and● aren't one of Java's reserved words.
x w7thBookInTheSeries LOUD_AND_PROUDHarry Potter that'sACoolNamenoOrdinaryRabbit voidlots_of_underscores C_19_H_14_O_5_S
Variable Names
● Legal names for variables● begin with a letter or an underscore (_)● consist of letters, numbers, and underscores,
and● aren't one of Java's reserved words.
x w7thBookInTheSeries LOUD_AND_PROUDHarry Potter that'sACoolNamenoOrdinaryRabbit voidlots_of_underscores C_19_H_14_O_5_S
Variable Names
● Legal names for variables● begin with a letter or an underscore (_)● consist of letters, numbers, and underscores,
and● aren't one of Java's reserved words.
x w7thBookInTheSeries LOUD_AND_PROUDHarry Potter that'sACoolNamenoOrdinaryRabbit voidlots_of_underscores C_19_H_14_O_5_S
Variable Names
● Legal names for variables● begin with a letter or an underscore (_)● consist of letters, numbers, and underscores,
and● aren't one of Java's reserved words.
x w7thBookInTheSeries LOUD_AND_PROUDHarry Potter that'sACoolNamenoOrdinaryRabbit voidlots_of_underscores C_19_H_14_O_5_S
Variable Names
● Legal names for variables● begin with a letter or an underscore (_)● consist of letters, numbers, and underscores,
and● aren't one of Java's reserved words.
x wLOUD_AND_PROUD
noOrdinaryRabbit lots_of_underscores C_19_H_14_O_5_S
Variable Naming Conventions
● You are free to name variables as you see fit, but there are some standard conventions.
● Names are often written in lower camel case:
capitalizeAllWordsButTheFirst
Choose names that describe what the variable does.
If it's a number of votes, call it numberOfVotes, numVotes, votes, etc.
Don't call it x, volumeControl, or severusSnape
Variable Naming Conventions
● You are free to name variables as you see fit, but there are some standard conventions.
● Names are often written in lower camel case:
capitalizeAllWordsButTheFirst
Choose names that describe what the variable does.
If it's a number of votes, call it numberOfVotes, numVotes, votes, etc.
Don't call it x, volumeControl, or
Variable Naming Conventions
● You are free to name variables as you see fit, but there are some standard conventions.
● Names are often written in lower camel case:
capitalizeAllWordsButTheFirst
Choose names that describe what the variable does.
If it's a number of votes, call it numberOfVotes, numVotes, votes, etc.
Don't call it x, volumeControl, or
Variable Naming Conventions
● You are free to name variables as you see fit, but there are some standard conventions.
● Names are often written in lower camel case:
capitalizeAllWordsButTheFirst ● Choose names that describe what the variable does.
● If it's a number of voters, call it numberOfVoters, numVoters, voters, etc.
● Don't call it x, volumeControl, or severusSnape.
Types
● The type of a variable determines what can be stored in it.
● Java has several primitive types that it knows how to understand:
Types
● The type of a variable determines what can be stored in it.
● Java has several primitive types that it knows how to understand:● int: Integers.
Types
● The type of a variable determines what can be stored in it.
● Java has several primitive types that it knows how to understand:● int: Integers.● double: Real numbers.
Types
● The type of a variable determines what can be stored in it.
● Java has several primitive types that it knows how to understand:● int: Integers.● double: Real numbers.● boolean: Logical true and false.●
Types
● The type of a variable determines what can be stored in it.
● Java has several primitive types that it knows how to understand:● int: Integers. (counting)● double: Real numbers.● boolean
●
Types
● The type of a variable determines what can be stored in it.
● Java has several primitive types that it knows how to understand:● int: Integers. (counting)● double: Real numbers. (measuring)
Types
● The type of a variable determines what can be stored in it.
● Java has several primitive types that it knows how to understand:● int: Integers. (counting)● double: Real numbers. (measuring)● boolean: Logical true and false.● (Plus a few more)
Values
137 int numVotes
0.97333 double fractionVoting
0.64110 double fractionYes
Declaring Variables
● In Java, before you can use a variable, you need to declare it so that Java knows the name, type, and value.
● The syntax for declaring a variable is
type name = value; ● For example:
● int numVotes = 137;● double pricePerPound = 0.93;
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the summationprintln("The sum of those numbers is " + sum);
}}
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the summationprintln("The sum of those numbers is " + sum);
}}
Reading Values
● You can prompt the user for a value by using the readInt and readDouble methods.
● For example:int numBunnies = readInt("How many bunnies? ");
double weight = readDouble("Each bunny weighs? ");
● Notice that there's a space at the end of each of the prompts – we'll see why in a second.
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the summationprintln("The sum of those numbers is " + sum);
}}
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the summationprintln("The sum of those numbers is " + sum);
}}
Expressions
● Variables and other values can be used in expressions.
● Some familiar mathematical operators:● + (addition)
● – (subtraction)
● * (multiplication)
● / (division)
Operator Precedence
● Java's mathematical operators have the following precedence:
() (highest)
* /
+ - (lowest)
● Operators of equal precedence are evaluated left-to-right.
Red Squigglies
● In Alice, you programmed with drag-and-drop commands.
● In Java, you have to type everything in.● If you mistype something, you'll see it
underlined in red squigglies in Eclipse and your program won't run.
● This is called a syntax error. It's Java's way of saying “I don't understand what you want me to do.”
Red Squigglies
● Here are some common causes of red squigglies:● Forgetting a semicolon. For now, every line in your
program, except comments, should end in a semicolon. If you forget it, you'll get a red squiggly.
● Misspelling something. Java is case-sensitive, so int and Int are different things. If you capitalize something wrong or misspell it, you'll get red squigglies.
● At the back of the room we have set up the Wall of Bugs. If you get a red squiggly in your program, once you've fixed it, head back to that wall and write down what the problem was. If you get stuck, take a look at what people have written down – there might be some great things there!
Your Turn!
● Import the project Java 2 into Eclipse.● Your Task: Suppose that you own a grocery store
that sells apples. Your job is to write a program that prompts the user for the number of pounds of apples a customer bought and the price of apples, then prints the amount that the customer owes.
● Finished early? Try the basketball scoring problem. If you finished that early and are up for a challenge, try the Pythagorean Theorem problem!
Fun with Division
Rounding Down
● In Java, dividing two ints will divide and then round down.
● For example, this will print 3:
int value = 7 / 2;
println("The value is " + value);
● This might be a bit weird, but there's a good reason for it.
Sharing Cookies
She got morethan me!
Cookies for everyone!
The Mod Operator
● The special operator % (called the modulus operator or mod operator) computes the remainder of one value divided by another.
● a % b is pronouned “a mod b.”
● For example:● 15 % 3 = 0● 14 % 8 = 6● 21 % 2 = 1● 14 % 17 = 14
So… how do we take an average?
Dividing Doubles
● In Java, dividing two ints will divide and then round down.
● Dividing two doubles will do the division correctly.
● If either operand is a double, the division will be done correctly.
● For example, to compute the average of two ints n1 and n2, you could write
double average = (n1 + n2) / 2.0;
Your Turn
● Import the Java 3 project into Eclipse.● Your Task: Write a program that
determines the average speed you're traveling at when you take a trip somewhere.
● Finished early? Try the triangle area problem. If you finish that and are up for a challenge, try the change-making problem!
Programming with Graphics
Working with Graphics
● We will manipulate graphics on-screen by creating graphics objects and manipulating their properties.
● To create a graphics object, we need to● declare a variable to hold that object, and● actually create the object using the new
keyword.
● For example:
GLabel label = new GLabel("Hi!");
Sending Messages
● You can manipulate graphics objects by calling methods on those objects.
● To call a method on an object, use the syntax
object.method(parameters)
● For example:
label.setFont("Comic Sans-32");
label.setColor(Color.ORANGE);
Sending Messages
● You can manipulate graphics objects by calling methods on those objects.
● To call a method on an object, use the syntax
object.method(parameters)
● For example:
label.setFont("Comic Sans-32");
label.setColor(Color.ORANGE);
Sending Messages
● You can manipulate graphics objects by calling methods on those objects.
● To call a method on an object, use the syntax
object.method(parameters)
● For example:
label.setFont("Comic Sans-32");
label.setColor(Color.ORANGE);
Who?What?
What specifically?
Graphics Coordinates
HelloProgram
hello, world
+x
+y
Graphic courtesy of Eric Roberts
● Graphics objects are positioned by specifying an x and y coordinate.
● x increases left-to-right, y increases top-to-bottom.● x and y should be specified in pixels.● For a GLabel, the x and y coordinates give the start of the
baseline where the text is drawn.
Graphics Coordinates
HelloProgram
hello, world
+x
+y
Graphic courtesy of Eric Roberts
● Graphics objects are positioned by specifying an x and y coordinate.
● x increases left-to-right, y increases top-to-bottom.● x and y should be specified in pixels.● For a GLabel, the x and y coordinates give the start of the
baseline where the text is drawn.
(0, 0)
Graphics Coordinates
HelloProgram
hello, world
(100, 75)
+x
+y
Graphic courtesy of Eric Roberts
● Graphics objects are positioned by specifying an x and y coordinate.
● x increases left-to-right, y increases top-to-bottom.● x and y should be specified in pixels.● For a GLabel, the x and y coordinates give the start of the
baseline where the text is drawn.
(0, 0)
Drawing Geometrical Objects
Graphic courtesy of Eric Roberts
Graphics Program
Drawing Geometrical ObjectsConstructors new GRect( x, y, width, height)
Creates a rectangle whose upper left corner is at (x, y) of the specified size
Graphic courtesy of Eric Roberts
+x
+y
(x, y)
(x + width, y + height)
Drawing Geometrical ObjectsConstructors new GRect( x, y, width, height)
Creates a rectangle whose upper left corner is at (x, y) of the specified size
new GOval( x, y, width, height)Creates an oval that fits inside the rectangle with the same dimensions.
Graphic courtesy of Eric Roberts
Graphics Program
+x
+y
(x, y)
(x + width, y + height)
Drawing Geometrical ObjectsConstructors new GRect( x, y, width, height)
Creates a rectangle whose upper left corner is at (x, y) of the specified size
new GOval( x, y, width, height)Creates an oval that fits inside the rectangle with the same dimensions.
new GLine( x0, y0, x1, y1)Creates a line extending from (x0, y0) to (x1, y1).
Graphic courtesy of Eric Roberts
Graphics Program
+x
+y
(x0, y0)
(x1, y1)
Drawing Geometrical ObjectsConstructors new GRect( x, y, width, height)
Creates a rectangle whose upper left corner is at (x, y) of the specified size
new GOval( x, y, width, height)Creates an oval that fits inside the rectangle with the same dimensions.
Methods shared by the GRect and GOval classes object.setFilled( fill)
If fill is true, fills in the interior of the object; if false, shows only the outline.
object.setFillColor( color)Sets the color used to fill the interior, which can be different from the border.
new GLine( x0, y0, x1, y1)Creates a line extending from (x0, y0) to (x1, y1).
Graphic courtesy of Eric Roberts
The Collage Model
Your Turn!
● Import the Java 4 project into Eclipse.
● Your Task: Draw anything you want! Try to include at least one line, at least one oval, at least one rectangle, and at least one piece of text.
Computing with Graphics
Size of the Graphics Window
Methods provided by GraphicsProgram class getWidth()
Returns the width of the graphics window.
getHeight()
Returns the height of the graphics window.
Based on slides by Eric Roberts
Like println, readInt, and readDouble, you don't need to prefix these methods with the object. notation.
Making This Circle
Making This Circle
100 pixels
Making This Circle
100 pixels
Making This Circle
Where is this Where is this point?
100 pixels
Making This Circle
Where is this Where is this point?
getWidth() pixels
100 pixels
Making This Circle
Where is this Where is this point?
getWidth() pixels
double x = getWidth() - 100;
100
pixe
ls
Making This Circle
double x = getWidth() - 100;
100
pixe
ls
Making This Circle
double x = getWidth() - 100;
getH
eight()
pix
els
100
pixe
ls
Making This Circle
double x = getWidth() - 100;double y = getHeight() - 100;
getH
eight()
pix
els
100
pixe
ls
Making This Circle
double x = getWidth() - 100;double y = getHeight() - 100;
GOval circle = new GOval(x, y, 100, 100);
getH
eight()
pix
els
Making This Circle
double x = getWidth() - 100;double y = getHeight() - 100;
GOval circle = new GOval(x, y, 100, 100);
Making This Circle
double x = getWidth() - 100;double y = getHeight() - 100;
GOval circle = new GOval(x, y, 100, 100);circle.setFilled(true);circle.setColor(Color.BLUE);
Making This Circle
double x = getWidth() - 100;double y = getHeight() - 100;
GOval circle = new GOval(x, y, 100, 100);circle.setFilled(true);circle.setColor(Color.BLUE);add(circle);
Exploring the Coordinate Space
Your Turn!
● Import the Java 5 project into Eclipse.
● Your Task: Write a program that puts filled, black circles of radius 100 pixels in all four corners of the window.
● Finish early? Try the diamond and Belgian flag problems!
Graphics Program
Illusory Contours
Illusory Contours
Illusory Contours
Illusory Contours
Illusory Contours
Illusory Contours
50 50
Illusory Contours
50 getWidth() - 100 50
Magic Numbers
● A magic number is a number written in a piece of code whose meaning cannot easily be deduced from context.
double weight = 9.8 * (mass – 14.3);
● Magic numbers make code harder to readand harder to change.
Constants
● A constant is a name for a value that never changes.
● Syntax (defined outside of any method):
private static final type name = value;
● By convention, constants are named in UPPER_CASE_WITH_UNDERSCORES to differentiate them from variables.
● Constants can significantly improve code readability. They also improve code maintainability.
Centering an Object
Graphics Program
getWidth();
W
getWidth() / 2.0;
W / 2.0
double x = (getWidth() / 2.0) – (W / 2.0);
- or -
double x = (getWidth() - W) / 2.0;
More Coordinate Space Exploration!
Your Turn!
● Import the Java 6 project into Eclipse.
● Your Task: Write a program that draws the Flag of Paris centered in the screen.
● Each bar should be 100 pixels across and 200 pixels tall, so the total flag is of size 200 × 200.
● Finished early? Try the Snowman or No Dice problems!
Control Structures
Control Structures
● In our second day of Alice, we saw three control structures:● Counted Loops● While Loops● If Statements
● These exist in Java as well!● Let's see what they look like.
Control Structures
iffor
while
Control Structures
iffor
while
if statements
if (condition) {… statements to run if condition holds …} else {… statements to run if condition doesn't hold …}
Based on slides by Mehran Sahami
Boolean Expressions
● A boolean expression is a test for a condition (it is either true or false).
● Value comparisons:
== “equals” (note: not single =)
!= “not equals”
> “greater than”
< “less than”
>= “greater than or equal to”
<= “less than or equal to”
Or else
if (condition) {… statements to run if condition holds …} else {… statements to run if condition doesn't hold …}
A Note on Semicolons
● Notice that there isn't a semicolon after the parentheses in if statements.
● You'll get weird red squigglies if you accidentally put semicolons there.
if (condition) {… statements to run if condition holds …} else {… statements to run if condition doesn't hold …}
Logical Operators
● We can combine conditions with logical operators.● Logical NOT: !p
if (!isWeekday()) {
relaxAndUnwind();
}
● Logical AND: p && q if (youreHappy() && youKnowIt()) {
clapYourHands();
}
● Logical OR: p || q (inclusive OR)
if (hasPuppy() || hasKitty()) {
beHappy();
}
Cascading if
Based on slides by Mehran Sahami
if (score >= 90) { println(" AWWWW YEAHHHHH ");} else if (score >= 80) { println(" <(^_^)> ");} else if (score >= 70) { println(" : - | ");} else if (score >= 60) { println(" ಠ_ಠ ");} else {
println(" ( ° °╯ □ )╯︵ ┻━┻ ");}
Cascading if
Based on slides by Mehran Sahami
if (score >= 90) { println(" AWWWW YEAHHHHH ");} else if (score >= 80) { println(" <(^_^)> ");} else if (score >= 70) { println(" : - | ");} else if (score >= 60) { println(" ಠ_ಠ ");} else {
println(" ( ° °╯ □ )╯︵ ┻━┻ ");}
Cascading if
Based on slides by Mehran Sahami
if (score >= 90) { println(" AWWWW YEAHHHHH ");} else if (score >= 80) { println(" <(^_^)> ");} else if (score >= 70) { println(" : - | ");} else if (score >= 60) { println(" ಠ_ಠ ");} else {
println(" ( ° °╯ □ )╯︵ ┻━┻ ");}
Cascading if
Based on slides by Mehran Sahami
if (score >= 90) { println(" AWWWW YEAHHHHH ");} else if (score >= 80) { println(" <(^_^)> ");} else if (score >= 70) { println(" : - | ");} else if (score >= 60) { println(" ಠ_ಠ ");} else {
println(" ( ° °╯ □ )╯︵ ┻━┻ ");}
Cascading if
Based on slides by Mehran Sahami
if (score >= 90) { println(" AWWWW YEAHHHHH ");} else if (score >= 80) { println(" <(^_^)> ");} else if (score >= 70) { println(" : - | ");} else if (score >= 60) { println(" ಠ_ಠ ");} else {
println(" ( ° °╯ □ )╯︵ ┻━┻ ");}
Your Turn!
● Import Java 7 into Eclipse.● Your Task: Astronomers searching for planets
orbiting other stars like it when those planets' temperatures fall into the “habitable zone,” which we'll treat as between 32°F and 120°F.
● Write a program that prompts the user for the temperature of a planet and tells the user whether it's too hot, too cold, or in the habitable zone.
● Finished early? Try the Know Your Rights problem, and if you finish that, then try the Time Conversion problem!
Program Tracing
// Program 1import acm.program.*;
public class HabitableZone extends ConsoleProgram { private static final double MIN_TEMPERATURE = 32.0; private static final double MAX_TEMPERATURE = 120.0;
public void run() { double temp = readDouble("How hot? "); if (temp < MIN_TEMPERATURE) { println("Too cold!"); }
if (temp > MAX_TEMPERATURE) { println("Too hot!"); }
if (temp >= MIN_TEMPERATURE && temp <= MAX_TEMPERATURE) { println("Just right!"); } }}
// Program 2import acm.program.*;
public class HabitableZone extends ConsoleProgram { private static final double MIN_TEMPERATURE = 32.0; private static final double MAX_TEMPERATURE = 120.0;
public void run() { double temp = readDouble("How hot? "); if (temp < MIN_TEMPERATURE) { println("Too cold!"); }
if (temp >= MIN_TEMPERATURE && temp <= MAX_TEMPERATURE) { println("Just right!"); }
if (temp > MAX_TEMPERATURE) { println("Too hot!"); } }}
// Program 3import acm.program.*;
public class HabitableZone extends ConsoleProgram { private static final double MIN_TEMPERATURE = 32.0; private static final double MAX_TEMPERATURE = 120.0;
public void run() { double temp = readDouble("How hot? "); if (temp < MIN_TEMPERATURE) { println("Too cold!"); }
if (temp >= MIN_TEMPERATURE || temp <= MAX_TEMPERATURE) { println("Just right!"); }
if (temp > MAX_TEMPERATURE) { println("Too hot!"); } }}
// Program 4import acm.program.*;
public class HabitableZone extends ConsoleProgram { private static final double MIN_TEMPERATURE = 32.0; private static final double MAX_TEMPERATURE = 120.0;
public void run() { double temp = readDouble("How hot? "); if (temp < MIN_TEMPERATURE) { println("Too cold!"); } else if (temp > MAX_TEMPERATURE) { println("Too hot!"); } else if (temp >= MIN_TEMPERATURE && temp <= MAX_TEMPERATURE) { println("Just right!"); } }}
// Program 5import acm.program.*;
public class HabitableZone extends ConsoleProgram { private static final double MIN_TEMPERATURE = 32.0; private static final double MAX_TEMPERATURE = 120.0;
public void run() { double temp = readDouble("How hot? "); if (temp < MIN_TEMPERATURE) { println("Too cold!"); } else if (temp > MAX_TEMPERATURE) { println("Too hot!"); } else { println("Just right!"); } }}
// Program 6import acm.program.*;
public class HabitableZone extends ConsoleProgram { private static final double MIN_TEMPERATURE = 32.0; private static final double MAX_TEMPERATURE = 120.0;
public void run() { double temp = readDouble("How hot? "); if (temp > MAX_TEMPERATURE) { println("Too hot!"); } else if (temp < MIN_TEMPERATURE) { println("Too cold!"); } else { println("Just right!"); } }}
// Program 7import acm.program.*;
public class HabitableZone extends ConsoleProgram { private static final double MIN_TEMPERATURE = 32.0; private static final double MAX_TEMPERATURE = 120.0;
public void run() { double temp = readDouble("How hot? "); if (temp < MIN_TEMPERATURE) { println("Too cold!"); }
if (temp > MAX_TEMPERATURE) { println("Too hot!"); } else { println("Just right!"); } }}
// Program 8import acm.program.*;
public class HabitableZone extends ConsoleProgram { private static final double MIN_TEMPERATURE = 32.0; private static final double MAX_TEMPERATURE = 120.0;
public void run() { double temp = readDouble("How hot? "); if (temp > MAX_TEMPERATURE) { println("Too hot!"); } else { println("Just right!"); }
if (temp < MIN_TEMPERATURE) { println("Too cold!"); } }}
Control Statements
iffor
while
Control Statements
iffor
while
For Loops
● In Java, the for loop is used to repeat a statement a certain number of times.
● Similar to the loop construct from Alice, though is a bit more powerful.
● Today, we'll see some quick examples using for loops. When we come back next time, we'll explore how they work in more depth.
The Syntax
● To repeat a set of commands N times, use the following code:
for (int i = 0; i < N; i++) {
// … statements to execute …
}
● We'll talk about how exactly this works later on. For now, let's focus on what we can do with it!
Some Song Lyrics
● Let's write a program to print these lyrics:
Baby,
Baby,
Baby,
Ohhh
- Justin Bieber
Accessing the Counter
● Inside a for loop, the variable i keeps track of the index of the current loop, starting at 0.● First time through the loop: i = 0● Second time through the loop: i = 1● Third time through the loop: i = 2
● Let's see an example of this.
Accessing the Counter
● The different control structures in Java can be combined together to produce results more complex than any individual piece.
● For example, we can combine for loops and if statements together.
Accessing the Counter
● Suppose we want to print out the first fifteen multiples of 50 (0, 50, 100, …).
● We can accomplish this using a for loop.
for (int i = 0; i < 15; i++) {
println(i * 50);
}
● Do you see why?
Accessing the Counter
● Suppose we want to draw a row of boxes, like these:
● Suppose each box is 50 pixels wide and 50
pixels tall.● Look where their corners are... seem familiar?
Accessing the Counter
● Suppose we want to draw a row of boxes, like these:
● Suppose each box is 50 pixels wide and 50
pixels tall.● Look where their corners are... seem familiar?
(0, 0) (50, 0) (100, 0) (150, 0) (200, 0) (250, 0)
Your Turn!
● Download Java 8.
● Your Task: Draw a caterpillar! Start by drawing the body, which should consist of a bunch of circles. (Use a for loop!)
● Then, make it pretty however you'd like!
● Finished early, or want to try something else? Check out the Fizz Bazz Buzz problem. If you finish that and are up for a challenge, try the Seeing Stars program!
Double for Loops
Double for Loops
● Just as you can put if statements inside of for loops, you can put for loops inside of for loops!
● Syntax:
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
// … statements to execute …
}
}
● This will run through all possible combinations of i and j where i is less than M and j is less than N.
GRect box = new GRect(0, 0, BOX_SIZE, BOX_SIZE); box.setFilled(true); box.setFillColor(Color.BLUE); add(box);
GRect box = new GRect(0, 0, BOX_SIZE, BOX_SIZE); box.setFilled(true); box.setFillColor(Color.BLUE); add(box);
for (int j = 0; j < 5; j++) { double x = j * BOX_SIZE;
GRect box = new GRect(x, 0, BOX_SIZE, BOX_SIZE); box.setFilled(true); box.setFillColor(Color.BLUE); add(box); }
for (int j = 0; j < 5; j++) { double x = j * BOX_SIZE;
GRect box = new GRect(x, 0, BOX_SIZE, BOX_SIZE); box.setFilled(true); box.setFillColor(Color.BLUE); add(box); }
for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { double x = j * BOX_SIZE; double y = i * BOX_SIZE;
GRect box = new GRect(x, y, BOX_SIZE, BOX_SIZE); box.setFilled(true); box.setFillColor(Color.BLUE); add(box); }}
for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { double x = j * BOX_SIZE; double y = i * BOX_SIZE;
GRect box = new GRect(x, y, BOX_SIZE, BOX_SIZE); box.setFilled(true); box.setFillColor(Color.BLUE); add(box); }}
for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { double x = j * BOX_SIZE; double y = i * BOX_SIZE;
GRect box = new GRect(x, y, BOX_SIZE, BOX_SIZE); box.setFilled(true); box.setFillColor(Color.BLUE); add(box); }}
Your Turn!
● Import Java 9.
● Your Task: Draw this optical illusion!
● Each box is 50 × 50 with 10 additional pixels of horizontal and vertical spacing between each box.
● Think about the caterpillar – how might you adjust the spacing between these boxes?
● Finished early? Try the checkerboard or yarn pattern problems!
Variables, Revisited
The Story So Far
● We've now covered graphics programming, if statements, for loops, and the basics of variables.
● Before we can move on any further, we need to explore variables in more depth.
● This part might seem a bit counterintuitive, but it will unlock many doors.
Assignment Statements
● A variable consists of● a name (what is it called?),● a type (what sort of value does it hold?), and● a value.
● A variable's name and type can never change.
● However, it is possible to change the value stored in a variable.
Assignment Statements
● A statement of the form
variable = newValue;
changes variable so that it now stores newValue instead of its old value.
● This statement is called an assignment statement.
An Examplepublic void run() { int favoriteNumber = 3; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
3137179
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
3137179
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
3137179
4favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
3137179
4favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
4137179
4favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
4137179
4favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
4137179
137favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
4137179
137favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
4137179
137favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
4137179
137favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
4137179
179favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
4137179
179favoriteNumber
An Examplepublic void run() { int favoriteNumber = 4; println(favoriteNumber);
favoriteNumber = 137; println(favoriteNumber);
favoriteNumber = 137 + 42; println(favoriteNumber);}
Changing Variables
4137179
179favoriteNumber
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
1010
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
5a
7b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
5a
7b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
10a
7b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
10a
7b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
10a
7b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
10a
7b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
10a
5b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
10a
5b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
10a
5b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
10a
5b
Another Examplepublic void run() { int a = 5; int b = 7;
a = b + 3; println(a);
b = 5; println(a);}
Changing Variables
1010
10a
5b
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Guh, what? println(a);
a = a * 2; println(a);}
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Guh, what? println(a);
a = a * 2; println(a);}
Changing Variables
5612
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Guh, what? println(a);
a = a * 2; println(a);}
Changing Variables
5612
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Guh, what? println(a);
a = a * 2; println(a);}
Changing Variables
5612
5a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Guh, what? println(a);
a = a * 2; println(a);}
Changing Variables
5612
5a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Guh, what? println(a);
a = a * 2; println(a);}
Changing Variables
5612
5a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Um, what? println(a);
a = a * 2; println(a);}
Changing Variables
5612
5a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Um, what? println(a);
a = a * 2; println(a);}
Changing Variables
5612
6a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Um, what? println(a);
a = a * 2; println(a);}
Changing Variables
5612
6a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Um, what? println(a);
a = a * 2; println(a);}
Changing Variables
5612
6a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Um, what? println(a);
a = a * 2; // <--- Seriously? println(a);}
Changing Variables
5612
6a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Um, what? println(a);
a = a * 2; // <--- Seriously? println(a);}
Changing Variables
5612
12a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Um, what? println(a);
a = a * 2; // <--- Seriously? println(a);}
Changing Variables
5612
12a
Another Examplepublic void run() { int a = 5; println(a);
a = a + 1; // <--- Um, what? println(a);
a = a * 2; // <--- Seriously? println(a);}
Changing Variables
5612
12a
Nudging Values
● In Java (and many other languages), it's normal to see statements like these:
x = x + 1;
y = y / 137;
● Don't read these as mathematical statements – you'll just get confused.
● Two intuitions:● Read these statements as “add one to x” or “divide y
by 137.”● Read these statements as commands – we are
ordering x and y to update the values they are storing.
Your Turn!
Why would you do this?
Write a program that reads in a list of five values, then outputs their sum.
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
0total
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
0total
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
0total
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
0total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
0total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
0total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
27nextValue
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
0total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
27nextValue
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
27total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
27nextValue
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
27total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
27total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
27total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
27total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
27total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
27total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
18nextValue
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
27total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
18nextValue
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
45total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
18nextValue
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
45total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
45total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
45total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
45total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
45total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
45total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
28nextValue
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
45total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
28nextValue
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
73total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
28nextValue
public void run() { int total = 0; for (int i = 0; i < 5; i++) { int nextValue = readInt("Enter next number: ");
/* Add the next value to the total. */ total = total + nextValue; } println("The total is " + total);}
SumFiveValues
73total
Enter next number: 27Enter next number: 18Enter next number: 28Enter next number: 18Enter next number: 28The total is 119
Aggregating Information
● It's extremely common to aggregate information across multiple iterations of a loop.
● General pattern:● If information needs to persist across loop
iterations, store it in a variable defined outside the loop.
● If information only needs to survive for a single iteration of the loop, define it inside the loop.
Your Turn!
● Import Java 10.
● Your Task: The American Heart Association recommends that everyone get 150 minutes of aerobic exercise every week.
● Write a program that prompts the user to enter the amount of aerobic exercise they did on each of the seven days of the week, then reports their total aerobic exercise.
● If the user hasn't gotten 150 minutes of aerobic exercise, tell them how many more minutes of exercise they need.
● Finished early? There's some instructions in the source file about some other things to check for. Update your program to also track that other information. If you finish that early, try the medicine half-lives program!
A Useful Shorthand
● Commonly, programs contain code like this:
x = x + 1; y = y * 137;
z = z / 14; w = w – 3;
A Useful Shorthand
● Commonly, programs contain code like this:
x = x + 1; y = y * 137;
z = z / 14; w = w – 3;
● The statement
variable = variable op value;
can be rewritten as
variable op= value;
A Useful Shorthand
● Commonly, programs contain code like this:
x += 1; y *= 137;
z /= 14; w -= 3;
● The statement
variable = variable op value;
can be rewritten as
variable op= value;
Another Useful Shorthand
● In the special case of writing
variable = variable + 1;
we can instead write
variable++;● In the special case of writing
variable = variable - 1;
we can instead write
variable--;
++: Seem Familiar?
● Hmmm... haven't we seen this ++ thing somewhere before?
● How about in
for (int i = 0; i < N; i++) {
…
}
● What does this mean?
for (int i = 0; i < N; i++) {…
}
This is called the initialization statement and is performed before
This is called the initialization statement and is performed before
the loop starts.
This is called the loop condition or termination condition. The loop will check whether this
statement is true before each
This is called the loop condition or termination condition. The loop will check whether this
statement is true before each iteration of the loop.
This is called the step or increment and is performed at the end
This is called the step or increment and is performed at the end of each loop iteration.
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
0int i
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
0int i
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
0int i
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
0int i
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
0int i
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
1int i
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
1int i
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
1int i
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
1int i
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
1int i
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
2int i
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
2int i
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
2int i
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
2int i
Baby
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
2int i
Baby
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
3int i
Baby
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
3int i
Baby
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
3int i
Baby
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
Baby
Baby
Baby
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
Baby
Baby
Baby
Ohhh
Console Program
Baby
Baby
Baby
Ohhh
for (int i = 0; i < 3; i++) { println("Baby"); } println("Ohhh");
Console Program
for (int i = 5; i > 0; i--) { println(i + "..."); } println("Lift-off!");
5...
4...
3...
2...
1...
Lift-off!
Control Statements
iffor
while
Control Statements
iffor
while
The while Loop
while (condition) {
… statements …
}
● This loop works as follows:● Check whether condition is true.● If so, execute statements in their entirety,
then repeat this process.● If not, move on to whatever comes after the
loop.
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Based on slides by Mehran Sahami
Console Program
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
15 int x
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
15 int x
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
15 int x
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
7 int x
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
7 int x
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
7 int x
7
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
7 int x
7
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
7 int x
7
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
3 int x
7
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
3 int x
7
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
3 int x
73
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
3 int x
73
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
3 int x
73
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
1 int x
73
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
1 int x
73
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
1 int x
731
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
1 int x
731
Based on slides by Mehran Sahami
The while Loop
int x = 15; while (x > 1) { x /= 2; println(x); }
Console Program
1 int x
731
Based on slides by Mehran Sahami
Infinite Loops
Your Turn!
● Import Java 11.
● Your Task: Start with any positive whole number. If that number is even, divide it by two. If it's odd, multiply it by three and add one. You then repeat this process until the number becomes one. Write a program that prompts the user for a number, then prints out this sequence beginning at that number. For example, starting at 13, the sequence is
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1● Finished early? Try the powers of two problem. If
you finish early, try the Fibonacci numbers problem!
Randomness and Computing
Random Number Generators
RandomGenerator
● The class RandomGenerator acts as a random number generator. To use it, you'll need to import acm.util.*;
● To generate random numbers, start by getting a random generator:
RandomGenerator rgen = RandomGenerator.getInstance();
● Then, use the nextX functions to get the random values you want:● rgen.nextInt(low, high)● rgen.nextDouble(low, high)● rgen.nextBoolean(probability)● rgen.nextColor() // Ooh, shiny!
Your Turn!
● Import Java 12.
● Your Task: Write a program that flips coins until it flips three heads and three tails, then reports the number of necessary flips.
● Finished early? Try the consecutive heads problem or the coin flipping game problem!
Writing Your Own Methods
● To define your own custom method, you can usethis syntax:
private void methodName() {
/* … Method body … */
}
● This code needs to go outside of the run method; Java will get sad otherwise.
● You can call your method by writing
methodName();
Defining Your Own Methods
Lord of the Rings
private void methodName() {
/* … Method body … */
}
methodName();
Methods With Parameters
● To define a method that takes some number of parameters, you can write
private void methodName(parameters) {
/* … method body … */
}
● These parameters behave like Alice parameters – you specify them when you call the method.
Methods and Parameters
● A while back, we said that every variable has three pieces of information associated with it. What are they?● Name● Type● Value
● When writing a method that takes parameters:● The method specifies the name and type of each
parameter.● The caller specifies the value.
Scope of Method Calls
● A variable declared inside a method is called a local variable.
● Local variables can only be accessed inside of the method that declares them.
public void run() {
int x = 5;
someOtherMethod();
}
private void someOtherMethod() {
x = 4; // Error!
}
More Method Examples
Drawing a Stoplight
Methods and Parameters
● When you are implementing a method, trust that the parameters provided are correct, then use them in the method to provide the desired behavior.
● When you are calling a method, trust that the method works correctly, then provide the necessary information as arguments.
● The implementer trusts the parameters and needs to ensure the method works right.
● The caller trusts the method and needs to ensure that the parameters are right.
Your Turn!
● Import Java 13.● Your Task: Write a method
that prints out a row of stars. Our provided starter code will then use it to print a pyramid of stars!
● Once you're done, switch to the Pawprints program and write a method that draws a pawprint at an (x, y) coordinate of your choice.
● Then, draw some animal tracks with your method!
● Finished early? Try the soccer field problem!
(x, y)
Review: Methods with Parameters
···*·····***···*****·*******·*****···***·····*···
···*·····***···*****·*******·*****···***·····*···
····*···· ···***··· ··*****·· ·*******· ********* ·*******· ··*****·· ···***··· ····*···
···*·····***···*****·*******·*****···***·····*···
···*·····***···*****·*******·*****···***·····*···
···*·····***···*****·*******·*****···***·····*···
number-of-stars + number-of-spaces = width
number-of-stars + 2 · spaces-to-draw = width
2 · spaces-to-draw = width – number-of-stars
spaces-to-draw = (width – number-of-stars) / 2
Methods that Return Values
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
import acm.program.*;
public class AddTwoIntegers extends ConsoleProgram {public void run() {
println("This program adds two integers.");
// Read two values from the user.int n1 = readInt("Enter first integer: ");int n2 = readInt("Enter second integer: ");
// Compute their sum.int sum = n1 + n2;
// Print out the sum.println("The sum of those numbers is " + sum);
}}
Return Values
● Methods can return values that can be used elsewhere in the program.
● Examples:● The getWidth and getHeight methods return the
width and height of the window.● The readInt and readDouble methods return
values entered by the user.
● You can write your own methods that return values!
Return Syntax
● To make a method that communicates a value to the outside world, you need to do two things.
● First, say what kind of value you want to communicate back by specifying a return type. Declare your method as
private returnType methodName(parameters)
● Then, include a return statement in your method saying what value to hand back.
return value;
Factorials!
● The number n factorial, denoted n!, is
1 × 2 × 3 × … × (n – 1) × n ● For example:
● 3! = 1 × 2 × 3 = 6.● 5! = 1 × 2 × 3 × 4 × 5 = 120● 0! = 1 (by definition)
● Factorials arise surprisingly frequently in computer science:● Determining how quickly computers can sort a list of
values.● Analyzing the efficiency of various algorithms.
Many Happy returns
● A method may have multiple return statements. The method ends as soon as return is executed.
private int thisIsLegal(int x) {
if (x == 5) {
return 0;
} else {
return 1;
}
}
Many Happy returns
● A method may have multiple return statements. The method ends as soon as return is executed.
private int thisIsLegal(int x) {
if (x == 5) {
return 0;
}
return 1;
}
The only way we can get here is if x is not The only way we can
get here is if x is not equal to 5.
Your Turn!
● Import Java 14.● Your Task: First, write a method called max
that takes in two ints and returns the larger of the two. Use our provided code in run to test it out.
● Next, write a raiseToPower method that takes in two integers a and b and computes the value ab. Use our provided code in run to test it out.
Variable Scoping
Scope
● Each variable has a scope where it can be accessed and how long it lives.
for (int i = 0; i < 5; i++) {
int y = i * 4;
println(y);
}
println(i); // Error!
println(y); // Error!
Scope
● Each variable has a scope where it can be accessed and how long it lives.
● Variables declared outside a loop persist across all loop iterations.
● Variables declared inside a loop persist only for a single iteration.
● The loop counter in a for loop persists as long as the loop runs, then disappears.
● General rule: A variable's scope is determined by the curly braces it lives in.
Scope of Method Calls
● A variable declared inside a method is called a local variable.
● Local variables can only be accessed inside of the method that declares them.
public void run() {
int x = 5;
someOtherMethod();
}
private void someOtherMethod() {
x = 4; // Error!
}
Scoping Revisited
● Variables defined in one method aren't visible inside of other methods.
● You can send values into a method by using parameters.
● You can receive values from a method by using return values.
● This can lead to some slightly unusual results.
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
result0n i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result0n i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result0n 1i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result0n 1i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result0n 1i
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0i
1
Slides by Mehran Sahami
Console Program
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0i
1
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
1i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
1i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
1i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
1i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
result1n i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result1n i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result1n 1i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result1n 1i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result1n 1i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result1n 2i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result1n 2i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result1n 2i
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
1i
1
Slides by Mehran Sahami
Console Program
0! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
1i
1
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
2i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
2i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
2i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
2i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
result2n i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result2n i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result2n 1i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result2n 1i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result2n 1i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result2n 2i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
1result2n 2i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
2result2n 2i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
2result2n 3i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
2result2n 3i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
0
i
private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
2result2n 3i
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
2i
2
Slides by Mehran Sahami
Console Program
0! = 11! = 1
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
2i
2
Slides by Mehran Sahami
Console Program
0! = 11! = 12! = 2
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
3i
Slides by Mehran Sahami
Console Program
0! = 11! = 12! = 2
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
3i
Slides by Mehran Sahami
Console Program
0! = 11! = 12! = 2
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
3i
Slides by Mehran Sahami
Console Program
0! = 11! = 12! = 2
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
3i
Slides by Mehran Sahami
Console Program
0! = 11! = 12! = 2
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
3i
6
Slides by Mehran Sahami
Console Program
0! = 11! = 12! = 2
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
3i
6
Slides by Mehran Sahami
Console Program
0! = 11! = 12! = 23! = 6
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
4i
Slides by Mehran Sahami
Console Program
0! = 11! = 12! = 23! = 6
public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); } }
4i
Slides by Mehran Sahami
Console Program
0! = 11! = 12! = 23! = 6
Retiring Young
Pass-by-Value
● Method parameters act as their own variables. They are independent of any similarly-named variable in the calling method.
● This is called pass-by-value.
private void retireYoung(int myMoney) {
myMoney = 1000000000;
}
public void run() {
int myMoney = 42;
retireYoung(myMoney);
println(myMoney);
}
Pass-by-Value
● Method parameters act as their own variables. They are independent of any similarly-named variable in the calling method.
● This is called pass-by-value.
private void retireYoung(int myMoney) {
myMoney = 1000000000;
}
public void run() {
int myMoney = 42;
retireYoung(myMoney);
println(myMoney);
}
public void run() { int myMoney = 42; retireYoung(myMoney); println(myMoney); }
42myMoney
Pass-by-Value
● Method parameters act as their own variables. They are independent of any similarly-named variable in the calling method.
● This is called pass-by-value.
private void retireYoung(int myMoney) {
myMoney = 1000000000;
}
public void run() {
int myMoney = 42;
retireYoung(myMoney);
println(myMoney);
}
public void run() { int myMoney = 42; retireYoung(myMoney); println(myMoney); }
42
private void retireYoung(int myMoney) { myMoney = 1000000000; }
42myMoney
Pass-by-Value
● Method parameters act as their own variables. They are independent of any similarly-named variable in the calling method.
● This is called pass-by-value.
private void retireYoung(int myMoney) {
myMoney = 1000000000;
}
public void run() {
int myMoney = 42;
retireYoung(myMoney);
println(myMoney);
}
public void run() { int myMoney = 42; retireYoung(myMoney); println(myMoney); }
42
private void retireYoung(int myMoney) { myMoney = 1000000000; }
kaching!myMoney
Pass-by-Value
● Method parameters act as their own variables. They are independent of any similarly-named variable in the calling method.
● This is called pass-by-value.
private void retireYoung(int myMoney) {
myMoney = 1000000000;
}
public void run() {
int myMoney = 42;
retireYoung(myMoney);
println(myMoney);
}
public void run() { int myMoney = 42; retireYoung(myMoney); println(myMoney); }
42myMoney
Your Turn: Scoping Practice
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
jenny charlie
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
1jenny charlie 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
1jenny charlie 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
1jenny charlie 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
1jenny charlie 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
3jenny charlie 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
3jenny charlie 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
3jenny charlie 2
FindingJava
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
3jenny charlie 2
FindingJava
jenny = 3
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
3jenny charlie 2
FindingJava
jenny = 3
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
3jenny charlie 2
FindingJava
jenny = 3charlie = 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
nemo()
3jenny charlie 2
FindingJava
jenny = 3charlie = 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
FindingJava
jenny = 3charlie = 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
FindingJava
jenny = 3charlie = 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
FindingJava
jenny = 3charlie = 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
FindingJava
jenny = 3charlie = 2dory = 1
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
FindingJava
jenny = 3charlie = 2dory = 1
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
FindingJava
jenny = 3charlie = 2dory = 1marlin = 2
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); }
public class FindingJava extends ConsoleProgram { public void run() { int dory = 1; int marlin = 2; nemo(dory, marlin); println("dory = " + dory); println("marlin = " + marlin); } private void nemo(int jenny, int charlie) { jenny += charlie; println("jenny = " + jenny); println("charlie = " + charlie); } }
run()
1dory marlin 2
FindingJava
jenny = 3charlie = 2dory = 1marlin = 2
What to Do
● Trace through the programs one line at a time. Don't skip steps! You should read one line at a time, decide what it does, then make changes.
● Keep track of which method you're in. When creating a new variable, add a new box to the current method. When calling a method, make a box for that whole method. Remember that there can be different variables with the same name in different scopes!
● Keep track of the output produced by the program in a separate place. We recommend drawing and labeling one box as the console.
Animation
Moving Objects
● You can move or change graphics objects after you've added them. If you do, the changes will show up on the screen.
● If you have a graphics object obj, you can call obj.move(dx, dy) to shift the object over dx pixels to the left and dy pixels down.● dx and dy can be negative to move the object
right or up.
Animation
● By repositioning objects after they have been added to the canvas, we can create animations.
● General pattern for animation:
while (animation-not-finished) {
update graphics;
pause(pause-time);
}
A Simple Animation
● We're going to animate the sun moving across the sky.
● We'll use a GOval to represent the sun.● For fun, we'll make the background a
nice shade of sky blue.
Your Turn!
● Import Java 15.● Your Task: Create an
animation of the sun setting below the horizon!
● The sun should appear to dip below the horizon.
● The sun should stop moving when it's no longer visible.
Your Turn!
● Import Java 15.● Your Task: Create an
animation of the sun setting below the horizon!
● The sun should appear to dip below the horizon.
● The sun should stop moving when it's no longer visible.
Physics Simulation
Δx
Δy Δx
Δy Δx
Δy Δx
Δy
Note that Δy increases because the object is accelerating
downward.Thanks, gravity!
Note that Δy increases because the object is accelerating
downward.Thanks, gravity!
A Falling Object
Bouncing Ball
ball.getY()
ball.getHeight()
getHeight()
A Sticky Situation
The ball is below the ground, so we reverse its yΔ
The ball is below the ground, so we reverse its yΔ
It's still below the ground, so we
reverse its y again.Δ
It's still below the ground, so we
reverse its y again.Δ
Your Turn!
● Import Java 16.● Your Task: Make
any animation that you'd like!
● Be creative! What can you come up with?
Events
Events
● An event is some external stimulus that your program can respond to.
● Common events include:● Mouse motion / clicking.● Keyboard buttons pressed.● Timers expiring.● Network data available.
Events
An event is some external stimulus that your program can respond to.
Common events include:● Mouse motion / clicking.
Keyboard buttons pressed.
Timers expiring.
Network data available.
Responding to Mouse Events
● To respond to events, your program must● indicate that it wants to receive events, and● write methods to handle those events.
● Call the addMouseListeners() method to tell your program receive mouse events.● This is typically done in run.
● Write appropriate methods to process the mouse events.
Methods for Handling Events
● Define any or all of the following mouse event handlers to respond to the mouse:
@Override public void mouseMoved(MouseEvent e)
@Override public void mouseDragged(MouseEvent e)
@Override public void mousePressed(MouseEvent e)
@Override public void mouseReleased(MouseEvent e)
@Override public void mouseClicked(MouseEvent e)
@Override public void mouseEntered(MouseEvent e)
@Override public void mouseExited(MouseEvent e)● Notice that these are public void and not private void. This is
important! Also notice the @Override prefix.● You must also import java.awt.event.*; for the MouseEvent class.
A Virtual Hole Puncher
The Mirror Box
Making the Mirror Box
MirrorBox
MirrorBox
MirrorBox
MirrorBox
(x, y)
MirrorBox
(x, y)
(??, ??)
MirrorBox
(x, y)
(??, y)
MirrorBox
(x, y)
x
(??, y)
x
MirrorBox
(x, y)
x
(getWidth() - x, y)
x
Your Turn!
● Import Java 17.● Your Task: Write a program
that places bear tracks wherever the mouse is clicked.
● We've provided a drawBearTrack method that, given an x and y coordinate, draws a bear track centered at that location.
● Finished early? Try the event visualizer problem or the color Theremin problem!
Boolean Values
Boolean Values
● A boolean value is a value that is either true or false.● In Java, you can store boolean values using the boolean
type.● Example:
int n = readInt("Enter an integer: ");
boolean isEven = (n % 2 == 0);
if (isEven) {
… }
Predicates
● Methods can return boolean values.● In CS, we use the fancy term predicate
to refer to a method that returns a boolean value.
● Because predicates return booleans, we can use them in if statements, for loops, and other contexts.
Prime Numbers
● An integer greater than 1 is called prime if its only divisors are 1 and itself.
● For example:● 5 is prime.● 17 is prime.● 15 is not prime: it's 3 × 5● 24 is not prime: it's 2 × 12, 3 × 8, and 4 × 6.
A Note about Programming Languages
Java and Python
private void isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i < n; i++) { if (n % i == 0) { return false; } } return true;}
def isPrime(n): if n <= 1: return False
for i in range(2, n): if n % i == 0: return False
return True
Interacting with the Canvas
Accessing the Canvas
● It is possible to determine what, if anything, is at the canvas at a particular point.
● The method
GObject getElementAt(double x, double y)
returns which object is at the given location on the canvas.
The return type is GObject, since we don't know what specific type (GRect, GOval, etc.) is really there.
If no object is present, the special value null is returned.
GObject
GRect GOval GLineGLabel
Accessing the Canvas
● It is possible to determine what, if anything, is at the canvas at a particular point.
● The method
GObject getElementAt(double x, double y)
returns which object is at the given location on the canvas.
● The return type is GObject, since we don't know what specific type (GRect, GOval, etc.) is really there.
● If no object is present, the special value null is returned.
A Debris Sweeper
Your Turn!
● Import Java 18.
● Your Task: Write a program that draws random circles on the screen that move when they're clicked on.
● Finished early and up for a challenge? Try the circle subdivision problem!
● As a hint, remember that you can ask an object for its position and size with obj.getX(), obj.getY(), obj.getWidth(), and obj.getHeight().
Your Turn!
● Import Java 18.
● Your Task: Write a program that draws random circles on the screen that move when they're clicked on.
● Finished early and up for a challenge? Try the circle subdivision problem!
● As a hint, remember that you can ask an object for its position and size with obj.getX(), obj.getY(), obj.getWidth(), and obj.getHeight().
Your Turn!
● Import Java 18.
● Your Task: Write a program that draws random circles on the screen that move when they're clicked on.
● Finished early and up for a challenge? Try the circle subdivision problem!
● As a hint, remember that you can ask an object for its position and size with obj.getX(), obj.getY(), obj.getWidth(), and obj.getHeight().
Your Turn!
● Import Java 18.
● Your Task: Write a program that draws random circles on the screen that move when they're clicked on.
● Finished early and up for a challenge? Try the circle subdivision problem!
● As a hint, remember that you can ask an object for its position and size with obj.getX(), obj.getY(), obj.getWidth(), and obj.getHeight().
Your Turn!
● Import Java 18.
● Your Task: Write a program that draws random circles on the screen that move when they're clicked on.
● Finished early and up for a challenge? Try the circle subdivision problem!
● As a hint, remember that you can ask an object for its position and size with obj.getX(), obj.getY(), obj.getWidth(), and obj.getHeight().
Fields
A Friendly CircleGraphics Program
Fields
● A field (or instance variable) is a variable that can be read or written by any of the methods of a class.
● Syntax (defined outside of any method):
private type name;
● When using fields inside a method, just use its name, not its type.
Working with Images
● The GImage type is a graphics type that stores an image loaded from disk.
● To create a GImage, specify the name of the file you want to load like this:
GImage variableName = new GImage("filename");
● This will search the current directory for the file you're looking for. You'll need to move or copy the files into the appropriate directory to do this.
● You can add GImages to the canvas the same way that you add other objects and can move and resize them as usual.
A Picture Reveal Game
RevealPuzzle
Sketchpad
Sketchpad
Sketchpad
Sketchpad
Clicking and Dragging
SuchADrag
SuchADrag
SuchADrag
SuchADrag
SuchADrag
SuchADrag
SuchADrag
SuchADrag
SuchADrag
Your Turn!
● Import Java 19.
● Your Task: Right now, our mouse tracker can move the cat out of the window.
● Update the mouse tracker so that the cat picture always stays within the bounds of the window.
● Finish early? Update the Mirror Box so that it draws continuous lines. Or take one of your previous drawings and make it interactive!
MouseTracker
Project: Breakout!