What is Java? professional software engineering.

Size: px
Start display at page:

Download "What is Java? professional software engineering."

Transcription

1 Welcome Back!

2 Welcome to Java!

3 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 secondmost-widely used language in professional software engineering.

4 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.

5 Our First Java Program

6 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!

7 Step One: Download the Project Go to and click on Java Projects.

8 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!

9 Step Three: Move the Files Copy the directory you extracted somewhere convenient (we recommend the desktop.)

10 Step Four: Import the Project Click on the Import button, which looks like this: Navigate to the folder Java01 and click Finish.

11 Step Five: Open the Source Files Navigate in the project to Default Package and double-click on the Java source file AddTwoIntegers.java

12 Step Six: Run the Program! Click on the icon of a little running guy. The program should start running!

13 Dissecting our Program

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

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

16 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. This This Java Java code code needs needs to to be be in in every every println("the sum of those program program numbers we'll we'll is " write write + sum); in in these these next next two two weeks. weeks. Because Because of of this, this, it's it's often often called called boilerplate boilerplate code. code. We'll We'll provide provide this this code code for for you you so so that you don't have to type it.

17 import acm.program.*; public class AddTwoIntegers extends ConsoleProgram { public void run() { println("this program adds two integers."); This This is is the the name name of of the the // Read two values from program. program. the user. Since Since this this program program int n1 = readint("enter adds adds two first two integers, integers, integer: I've I've "); named named it it int n2 = readint("enter second AddTwoIntegers. integer: "); // Compute their sum. int sum = n1 + n2; // Print out the sum. println("the sum of those numbers is " + sum);

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

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

20 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 This is is the the run run method. method. It's It's the the actual actual program to run.

21 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; Each Each of of these these lines lines of of code code is is called called a statement. statement. Each Each statement ends with a semicolon. // Print out the sum. println("the sum of those numbers is " + sum);

22 import acm.program.*; public class AddTwoIntegers extends ConsoleProgram { public void run() { println("this program adds two integers."); // Read two values from The the user. int n1 = readint("enter The println first println method integer: method (print "); (print line) line) displays int n2 = readint("enter second displays a integer: line line of of text "); text on on the the screen. screen. The The quoted quoted text text in in the the parentheses // Compute their sum. parentheses is is the the argument argument to to the method. int sum = n1 + n2; // Print out the sum. println("the sum of those numbers is " + sum);

23 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; These // Print out the sum. These statements statements are are called called variable println("the sum of those variable declarations. numbers declarations. They is " + sum); They allow allow us us to to give give names names to to quantities quantities (here, (here, the the first first two two numbers numbers entered and their sum).

24 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 These are are comments, comments, just just like like in in Alice. Alice. (Notice (Notice that that they still start with //).

25 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.

26 Variables A variable is a location where a program can store information for later use.

27 Variables A variable is a location where a program can store information for later use.

28 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:

29 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?

30 Variables A variable is a location where a program can store information for later use. int numvoters 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?

31 Variables A variable is a location where a program can store information for later use. int numvoters 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?

32 Variables A variable is a location where a program can store information for later use. int numvoters 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?

33 Variables A variable is a location where a program can store information for later use. int numvoters 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?

34 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? 137 int numvoters Value: What value does the variable have at any particular moment in time?

35 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? 137 int numvoters Value: What value does the variable have at any particular moment in time?

36 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 7thBookInTheSeries Harry Potter noordinaryrabbit lots_of_underscores w LOUD_AND_PROUD that'sacoolname void C_19_H_14_O_5_S

37 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 7thBookInTheSeries Harry Potter noordinaryrabbit lots_of_underscores w LOUD_AND_PROUD that'sacoolname void C_19_H_14_O_5_S

38 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 7thBookInTheSeries Harry Potter noordinaryrabbit lots_of_underscores w LOUD_AND_PROUD that'sacoolname void C_19_H_14_O_5_S

39 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 7thBookInTheSeries Harry Potter noordinaryrabbit lots_of_underscores w LOUD_AND_PROUD that'sacoolname void C_19_H_14_O_5_S

40 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 7thBookInTheSeries Harry Potter noordinaryrabbit lots_of_underscores w LOUD_AND_PROUD that'sacoolname void C_19_H_14_O_5_S

41 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 7thBookInTheSeries Harry Potter noordinaryrabbit lots_of_underscores w LOUD_AND_PROUD that'sacoolname void C_19_H_14_O_5_S

42 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 7thBookInTheSeries Harry Potter noordinaryrabbit lots_of_underscores w LOUD_AND_PROUD that'sacoolname void C_19_H_14_O_5_S

43 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 noordinaryrabbit lots_of_underscores w LOUD_AND_PROUD C_19_H_14_O_5_S

44 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

45 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

46 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

47 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.

48 Types The type of a variable determines what can be stored in it. Java has several primitive types that it knows how to understand:

49 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.

50 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.

51 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.

52 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

53 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)

54 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)

55 Values 137 int numvotes double fractionvoting double fractionyes

56 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 For example: int numvotes = 137; type name = value; double priceperpound = 0.93;

57 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 summation println("the sum of those numbers is " + sum);

58 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 summation println("the sum of those numbers is " + sum);

59 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.

60 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 summation println("the sum of those numbers is " + sum);

61 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 summation println("the sum of those numbers is " + sum);

62 Expressions Variables and other values can be used in expressions. Some familiar mathematical operators: + (addition) (subtraction) * (multiplication) / (division)

63 Operator Precedence Java's mathematical operators have the following precedence: () (highest) * / + - (lowest) Operators of equal precedence are evaluated left-to-right.

64 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.

65 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!

66 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!

67 Fun with Division

68 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.

69 Sharing Cookies

70 She got more than me!

71

72 Cookies for everyone!

73 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

74 So how do we take an average?

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

76 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!

77 Programming with Graphics

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

79 Sending Messages You can manipulate graphics objects by calling methods on those objects. To call a method on an object, use the syntax For example: object.method(parameters) label.setfont("comic Sans-32"); label.setcolor(color.orange);

80 Sending Messages You can manipulate graphics objects by calling methods on those objects. To call a method on an object, use the syntax For example: object.method(parameters) label.setfont("comic Sans-32"); label.setcolor(color.orange);

81 Sending Messages You can manipulate graphics objects by calling methods on those objects. To call a method on an object, use the syntax For example: object.method(parameters) label.setfont("comic Sans-32"); label.setcolor(color.orange); Who? What? What specifically?

82 Graphics Coordinates 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. HelloProgram hello, world +x +y Graphic courtesy of Eric Roberts

83 Graphics Coordinates 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. HelloProgram +x (0, 0) hello, world +y Graphic courtesy of Eric Roberts

84 Graphics Coordinates 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. HelloProgram +x (0, 0) hello, world +y (100, 75) Graphic courtesy of Eric Roberts

85 Drawing Geometrical Objects Graphic courtesy of Eric Roberts

86 Drawing Geometrical Objects Constructors new GRect( x, y, width, height) Creates a rectangle whose upper left corner is at (x, y) of the specified size Graphics Program +x (x, y) +y Graphic courtesy of Eric Roberts (x + width, y + height)

87 Drawing Geometrical Objects Constructors 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. Graphics Program +x (x, y) +y Graphic courtesy of Eric Roberts (x + width, y + height)

88 Drawing Geometrical Objects Constructors 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( x 0, y 0, x 1, y 1 ) Creates a line extending from (x 0, y 0 ) to (x 1, y 1 ). Graphics Program +x (x 0, y 0 ) +y Graphic courtesy of Eric Roberts (x 1, y 1 )

89 Drawing Geometrical Objects Constructors 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( x 0, y 0, x 1, y 1 ) Creates a line extending from (x 0, y 0 ) to (x 1, y 1 ). 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. Graphic courtesy of Eric Roberts

90 The Collage Model

91 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.

92 Computing with Graphics

93 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. Like println, readint, and readdouble, you don't need to prefix these methods with the object. notation. Based on slides by Eric Roberts

94 Making This Circle

95 Making This Circle

96 Making This Circle 100 pixels

97 Making This Circle 100 pixels Where is this Where is this point?

98 Making This Circle getwidth() pixels 100 pixels Where Where is is this this point?

99 Making This Circle double x = getwidth() - 100; getwidth() pixels 100 pixels Where Where is is this this point?

100 100 pixels Making This Circle double x = getwidth() - 100;

101 100 pixels Making This Circle double x = getwidth() - 100; getheight() pixels

102 100 pixels Making This Circle double x = getwidth() - 100; double y = getheight() - 100; getheight() pixels

103 100 pixels Making This Circle double x = getwidth() - 100; double y = getheight() - 100; GOval circle = new GOval(x, y, 100, 100); getheight() pixels

104 Making This Circle double x = getwidth() - 100; double y = getheight() - 100; GOval circle = new GOval(x, y, 100, 100);

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

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

107 Exploring the Coordinate Space

108 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

109 Illusory Contours

110 Illusory Contours

111 Illusory Contours

112 Illusory Contours

113 Illusory Contours

114 Illusory Contours 50 50

115 Illusory Contours 50 getwidth()

116 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 read and harder to change.

117 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.

118 Centering an Object getwidth() / 2.0; getwidth(); Graphics Program W / 2.0 W double x = (getwidth() / 2.0) (W / 2.0); - or - double x = (getwidth() - W) / 2.0;

119 More Coordinate Space Exploration!

120 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 Finished early? Try the Snowman or No Dice problems!

121 Control Structures

122 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.

123 Control Structures if for while

124 Control Structures if for while

125 if statements if (condition) { statements to run if condition holds else { statements to run if condition doesn't hold

126 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

127 Or else if (condition) { statements to run if condition holds else { statements to run if condition doesn't hold

128 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

129 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();

130 Based on slides by Mehran Sahami Cascading if if (score >= 90) { println(" AWWWW YEAHHHHH "); else if (score >= 80) { println(" <(^_^)> "); else if (score >= 70) { println(" : - "); else if (score >= 60) { println(" ಠ_ಠ "); else { println(" ( ) ( ");

131 Based on slides by Mehran Sahami Cascading if if (score >= 90) { println(" AWWWW YEAHHHHH "); else if (score >= 80) { println(" <(^_^)> "); else if (score >= 70) { println(" : - "); else if (score >= 60) { println(" ಠ_ಠ "); else { println(" ( ) ( ");

132 Based on slides by Mehran Sahami Cascading if if (score >= 90) { println(" AWWWW YEAHHHHH "); else if (score >= 80) { println(" <(^_^)> "); else if (score >= 70) { println(" : - "); else if (score >= 60) { println(" ಠ_ಠ "); else { println(" ( ) ( ");

133 Based on slides by Mehran Sahami Cascading if if (score >= 90) { println(" AWWWW YEAHHHHH "); else if (score >= 80) { println(" <(^_^)> "); else if (score >= 70) { println(" : - "); else if (score >= 60) { println(" ಠ_ಠ "); else { println(" ( ) ( ");

134 Based on slides by Mehran Sahami Cascading if if (score >= 90) { println(" AWWWW YEAHHHHH "); else if (score >= 80) { println(" <(^_^)> "); else if (score >= 70) { println(" : - "); else if (score >= 60) { println(" ಠ_ಠ "); else { println(" ( ) ( ");

135 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!

136 Program Tracing

137 // Program 1 import 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!");

138 // Program 2 import 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!");

139 // Program 3 import 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!");

140 // Program 4 import 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!");

141 // Program 5 import 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!");

142 // Program 6 import 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!");

143 // Program 7 import 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!");

144 // Program 8 import 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!");

145 Control Statements if for while

146 Control Statements if for while

147 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.

148 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!

149 Some Song Lyrics Let's write a program to print these lyrics: Baby, Baby, Baby, Ohhh - Justin Bieber

150 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.

151 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.

152 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++) { Do you see why? println(i * 50);

153 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?

154 Accessing the Counter Suppose we want to draw a row of boxes, like these: (0, 0) (50, 0) (100, 0) (150, 0) (200, 0) (250, 0) Suppose each box is 50 pixels wide and 50 pixels tall. Look where their corners are... seem familiar?

155 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!

156 Double for Loops

157 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.

158

159 GRect box = new GRect(0, 0, BOX_SIZE, BOX_SIZE); box.setfilled(true); box.setfillcolor(color.blue); add(box);

160 GRect box = new GRect(0, 0, BOX_SIZE, BOX_SIZE); box.setfilled(true); box.setfillcolor(color.blue); add(box);

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

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

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

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

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

166 Your Turn! Import Java 9. Your Task: Draw this optical illusion! Each box is 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!

167 Variables, Revisited

168 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.

169 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.

170 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.

171 An Example public void run() { int favoritenumber = 3; println(favoritenumber); favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

172 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

173 favoritenumber 4 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

174 favoritenumber 4 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

175 favoritenumber 4 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

176 favoritenumber 4 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

177 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber 137 favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

178 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber 137 favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

179 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber 137 favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

180 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber 137 favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

181 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber 179 favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

182 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber 179 favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

183 An Example public void run() { int favoritenumber = 4; println(favoritenumber); favoritenumber 179 favoritenumber = 137; println(favoritenumber); favoritenumber = ; println(favoritenumber); Changing Variables

184 Another Example public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); 10 10

185 Another Example public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables 10 10

186 Another Example public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables 10 10

187 Another Example a b 5 7 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

188 Another Example a b 5 7 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

189 Another Example a b 10 7 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

190 Another Example a b 10 7 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

191 Another Example a b 10 7 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

192 Another Example a b 10 7 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

193 Another Example a b 10 5 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

194 Another Example a b 10 5 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

195 Another Example a b 10 5 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

196 Another Example a b 10 5 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

197 Another Example a b 10 5 public void run() { int a = 5; int b = 7; a = b + 3; println(a); b = 5; println(a); Changing Variables

198 Another Example public void run() { int a = 5; println(a); a = a + 1; // <--- Guh, what? println(a); a = a * 2; println(a);

199 Another Example public void run() { int a = 5; println(a); a = a + 1; // <--- Guh, what? println(a); a = a * 2; println(a); Changing Variables

200 Another Example public void run() { int a = 5; println(a); a = a + 1; // <--- Guh, what? println(a); a = a * 2; println(a); Changing Variables

201 Another Example a 5 public void run() { int a = 5; println(a); a = a + 1; // <--- Guh, what? println(a); a = a * 2; println(a); Changing Variables

202 Another Example a 5 public void run() { int a = 5; println(a); a = a + 1; // <--- Guh, what? println(a); a = a * 2; println(a); Changing Variables

203 Another Example a 5 public void run() { int a = 5; println(a); a = a + 1; // <--- Guh, what? println(a); a = a * 2; println(a); Changing Variables

204 Another Example a 5 public void run() { int a = 5; println(a); a = a + 1; // <--- Um, what? println(a); a = a * 2; println(a); Changing Variables

205 Another Example a 6 public void run() { int a = 5; println(a); a = a + 1; // <--- Um, what? println(a); a = a * 2; println(a); Changing Variables

206 Another Example a 6 public void run() { int a = 5; println(a); a = a + 1; // <--- Um, what? println(a); a = a * 2; println(a); Changing Variables

207 Another Example a 6 public void run() { int a = 5; println(a); a = a + 1; // <--- Um, what? println(a); a = a * 2; println(a); Changing Variables

208 Another Example a 6 public void run() { int a = 5; println(a); a = a + 1; // <--- Um, what? println(a); a = a * 2; // <--- Seriously? println(a); Changing Variables

209 Another Example a 12 public void run() { int a = 5; println(a); a = a + 1; // <--- Um, what? println(a); a = a * 2; // <--- Seriously? println(a); Changing Variables

210 Another Example a 12 public void run() { int a = 5; println(a); a = a + 1; // <--- Um, what? println(a); a = a * 2; // <--- Seriously? println(a); Changing Variables

211 Another Example a 12 public void run() { int a = 5; println(a); a = a + 1; // <--- Um, what? println(a); a = a * 2; // <--- Seriously? println(a); Changing Variables

212 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.

213 Your Turn!

214 Why would you do this?

215 Write a program that reads in a list of five values, then outputs their sum.

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

217 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

218 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

219 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); total 0 SumFiveValues

220 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); total 0 SumFiveValues

221 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); total 0 SumFiveValues

222 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); total 0 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

223 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); total 0 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

224 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); total 0 nextvalue 27 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

225 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); total 0 nextvalue 27 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

226 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); total 27 nextvalue 27 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

227 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); total 27 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

228 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); total 27 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

229 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); total 27 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

230 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); total 27 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

231 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); total 27 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

232 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); total 27 nextvalue 18 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

233 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); total 27 nextvalue 18 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

234 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); total 45 nextvalue 18 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

235 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); total 45 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

236 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); total 45 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

237 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); total 45 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

238 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); total 45 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

239 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); total 45 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

240 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); total 45 nextvalue 28 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

241 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); total 45 nextvalue 28 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

242 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); total 73 nextvalue 28 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

243 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); total 73 SumFiveValues Enter next number: 27 Enter next number: 18 Enter next number: 28 Enter next number: 18 Enter next number: 28 The total is 119

244 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.

245 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!

246 A Useful Shorthand Commonly, programs contain code like this: x = x + 1; y = y * 137; z = z / 14; w = w 3;

247 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;

248 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;

249 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--;

250 ++: 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?

251 This This is is called called the the initialization initialization statement statement and and is is performed performed before before the loop starts. This This is is called called the the step step or or increment increment and and is is performed performed at at the the end end of each loop iteration. for (int i = 0; i < N; i++) { This This is is called called the the loop loop condition condition or or termination termination condition. condition. The The loop loop will will check check whether whether this this statement statement is is true true before before each each iteration of the loop.

252 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh");

253 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); Console Program

254 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); Console Program

255 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 0 Console Program

256 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 0 Console Program

257 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 0 Console Program

258 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 0 Baby Console Program

259 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 0 Baby Console Program

260 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 1 Baby Console Program

261 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 1 Baby Console Program

262 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 1 Baby Console Program

263 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 1 Console Program Baby Baby

264 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 1 Console Program Baby Baby

265 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 2 Console Program Baby Baby

266 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 2 Console Program Baby Baby

267 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 2 Console Program Baby Baby

268 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 2 Console Program Baby Baby Baby

269 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 2 Console Program Baby Baby Baby

270 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 3 Console Program Baby Baby Baby

271 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 3 Console Program Baby Baby Baby

272 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); int i 3 Console Program Baby Baby Baby

273 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); Baby Baby Baby Console Program

274 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); Baby Baby Baby Ohhh Console Program

275 for (int i = 0; i < 3; i++) { println("baby"); println("ohhh"); Baby Baby Baby Ohhh Console Program

276 for (int i = 5; i > 0; i--) { println(i + "..."); println("lift-off!"); Lift-off! Console Program

277 Control Statements if for while

278 Control Statements if for while

279 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.

280 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); Console Program

281 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); Console Program

282 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 15 int x Console Program

283 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 15 int x Console Program

284 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 15 int x Console Program

285 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 7 int x Console Program

286 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 7 int x Console Program

287 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 7 int x 7 Console Program

288 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 7 int x 7 Console Program

289 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 7 int x 7 Console Program

290 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 3 int x 7 Console Program

291 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 3 int x 7 Console Program

292 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 3 int x 7 3 Console Program

293 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 3 int x 7 3 Console Program

294 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 3 int x 7 3 Console Program

295 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 1 int x 7 3 Console Program

296 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 1 int x 7 3 Console Program

297 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 1 int x Console Program

298 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 1 int x Console Program

299 Based on slides by Mehran Sahami The while Loop int x = 15; while (x > 1) { x /= 2; println(x); 1 int x Console Program

300 Infinite Loops

301 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 Finished early? Try the powers of two problem. If you finish early, try the Fibonacci numbers problem!

302 Randomness and Computing

303 Random Number Generators

304 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!

305 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!

306 Writing Your Own Methods

307 Defining Your Own Methods To define your own custom method, you can use this 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();

308 Lord of the Rings private void methodname() { /* Method body */ methodname();

309 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.

310 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.

311 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!

312 More Method Examples

313 Drawing a Stoplight

314 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.

315 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)

316 Review: Methods with Parameters

317 * *** ***** ******* ***** *** *

318 * *** ***** ******* ***** *** *

319 * *** ***** ******* ********* ******* ***** *** *

320 * *** ***** ******* ***** *** *

321 * *** ***** ******* ***** *** *

322 * *** ***** ******* ***** *** * 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

323 Methods that Return Values

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

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

326 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!

327 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;

328 Factorials! The number n factorial, denoted n!, is (n 1) n For example: 3! = = 6. 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.

329 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) { else { return 0; return 1;

330 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 The only only way way we we can can get get here here is is if if x is is not not equal to 5.

331 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 a b. Use our provided code in run to test it out.

332 Variable Scoping

333 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!

334 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.

335 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!

336 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.

337 Slides by Mehran Sahami public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i Console Program

338 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 0 Console Program Slides by Mehran Sahami

339 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 0 Console Program Slides by Mehran Sahami

340 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 0 Console Program Slides by Mehran Sahami

341 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 0 Console Program Slides by Mehran Sahami

342 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 0 result i Console Program

343 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 0 result 1 i Console Program

344 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 0 result 1 i 1 Console Program

345 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 0 result 1 i 1 Console Program

346 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 0 result 1 i 1 Console Program

347 Slides by Mehran Sahami public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); 1 i 0 Console Program

348 Slides by Mehran Sahami public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); 1 i 0 0! = 1 Console Program

349 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 1 0! = 1 Console Program Slides by Mehran Sahami

350 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 1 0! = 1 Console Program Slides by Mehran Sahami

351 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 1 0! = 1 Console Program Slides by Mehran Sahami

352 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 1 0! = 1 Console Program Slides by Mehran Sahami

353 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 1 result i 0! = 1 Console Program

354 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 1 result 1 i 0! = 1 Console Program

355 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 1 result 1 i 1 0! = 1 Console Program

356 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 1 result 1 i 1 0! = 1 Console Program

357 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 1 result 1 i 1 0! = 1 Console Program

358 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 1 result 1 i 2 0! = 1 Console Program

359 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 1 result 1 i 2 0! = 1 Console Program

360 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 1 result 1 i 2 0! = 1 Console Program

361 Slides by Mehran Sahami public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); 1 i 1 0! = 1 Console Program

362 Slides by Mehran Sahami public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); 1 i 1 0! = 1 1! = 1 Console Program

363 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 2 0! = 1 1! = 1 Console Program Slides by Mehran Sahami

364 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 2 0! = 1 1! = 1 Console Program Slides by Mehran Sahami

365 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 2 0! = 1 1! = 1 Console Program Slides by Mehran Sahami

366 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 2 0! = 1 1! = 1 Console Program Slides by Mehran Sahami

367 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result i 0! = 1 1! = 1 Console Program

368 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 1 i 0! = 1 1! = 1 Console Program

369 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 1 i 1 0! = 1 1! = 1 Console Program

370 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 1 i 1 0! = 1 1! = 1 Console Program

371 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 1 i 1 0! = 1 1! = 1 Console Program

372 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 1 i 2 0! = 1 1! = 1 Console Program

373 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 1 i 2 0! = 1 1! = 1 Console Program

374 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 2 i 2 0! = 1 1! = 1 Console Program

375 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 2 i 3 0! = 1 1! = 1 Console Program

376 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 2 i 3 0! = 1 1! = 1 Console Program

377 Slides by Mehran Sahami public void run() { private for(int int i = factorial(int 0; i < MAX_NUM; n) i++) { { int println(i result + = "! 1; = " + factorial(i)); for (int i = 1; i <= n; i++) { result *= i; 0 return result; i n 2 result 2 i 3 0! = 1 1! = 1 Console Program

378 Slides by Mehran Sahami public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); 2 i 2 0! = 1 1! = 1 Console Program

379 Slides by Mehran Sahami public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); 2 i 2 0! = 1 1! = 1 2! = 2 Console Program

380 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 3 0! = 1 1! = 1 2! = 2 Console Program Slides by Mehran Sahami

381 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 3 0! = 1 1! = 1 2! = 2 Console Program Slides by Mehran Sahami

382 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 3 0! = 1 1! = 1 2! = 2 Console Program Slides by Mehran Sahami

383 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 3 0! = 1 1! = 1 2! = 2 Console Program Slides by Mehran Sahami

384 Slides by Mehran Sahami public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); 6 i 3 0! = 1 1! = 1 2! = 2 Console Program

385 Slides by Mehran Sahami public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); 6 i 3 0! = 1 1! = 1 2! = 2 3! = 6 Console Program

386 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 4 0! = 1 1! = 1 2! = 2 3! = 6 Slides by Mehran Sahami Console Program

387 public void run() { for(int i = 0; i < MAX_NUM; i++) { println(i + "! = " + factorial(i)); i 4 0! = 1 1! = 1 2! = 2 3! = 6 Slides by Mehran Sahami Console Program

388 Retiring Young

389 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 = ; public void run() { int mymoney = 42; retireyoung(mymoney); println(mymoney);

390 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 = ; public void run() { int mymoney = 42; retireyoung(mymoney); println(mymoney); public void run() { int mymoney = 42; retireyoung(mymoney); println(mymoney); mymoney 42

391 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 = ; public void run() { int mymoney = 42; retireyoung(mymoney); println(mymoney); public void run() { private int mymoney void = 42; retireyoung(int retireyoung(mymoney); { println(mymoney); = ; 42 mymoney 42

392 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 = ; public void run() { int mymoney = 42; retireyoung(mymoney); println(mymoney); public void run() { private int mymoney void = 42; retireyoung(int retireyoung(mymoney); { println(mymoney); = ; 42 mymoney kaching!

393 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 = ; public void run() { int mymoney = 42; retireyoung(mymoney); println(mymoney); public void run() { int mymoney = 42; retireyoung(mymoney); println(mymoney); mymoney 42

394 Your Turn: Scoping Practice

395 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie);

396 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie);

397 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run()

398 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run()

399 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1

400 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1

401 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2

402 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2

403 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2 jenny nemo() charlie

404 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2 nemo() jenny 1 charlie 2

405 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 1 charlie 2

406 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 1 charlie 2

407 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 1 charlie 2

408 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 3 charlie 2

409 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 3 charlie 2

410 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 3 charlie 2 FindingJava

411 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 3 charlie 2 jenny = 3 FindingJava

412 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 3 charlie 2 jenny = 3 FindingJava

413 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 3 charlie 2 jenny = 3 charlie = 2 FindingJava

414 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() nemo() dory 1 marlin 2 jenny 3 charlie 2 jenny = 3 charlie = 2 FindingJava

415 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2 jenny = 3 charlie = 2 FindingJava

416 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2 jenny = 3 charlie = 2 FindingJava

417 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2 jenny = 3 charlie = 2 FindingJava

418 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2 jenny = 3 charlie = 2 dory = 1 FindingJava

419 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2 jenny = 3 charlie = 2 dory = 1 FindingJava

420 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2 jenny = 3 charlie = 2 dory = 1 marlin = 2 FindingJava

421 public public class class FindingJava FindingJava extends extends ConsoleProgram {{ public public void void run() run() {{ int int dory dory = = 1; 1; int int marlin marlin = = 2; 2; nemo(dory, nemo(dory, marlin); marlin); println("dory = = "" + + dory); dory); println("marlin = = "" + + marlin); marlin); private private void void nemo(int nemo(int jenny, jenny, int int charlie) charlie) {{ jenny jenny += += charlie; charlie; println("jenny = = "" + + jenny); jenny); println("charlie = = "" + + charlie); charlie); run() dory 1 marlin 2 jenny = 3 charlie = 2 dory = 1 marlin = 2 FindingJava

422 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.

423 Animation

424 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.

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

426 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.

427 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.

428 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.

429 Physics Simulation

430 Δx A Falling Object Δy Δx Δy Δx Note Note that that Δy Δy increases increases because because the the object object is is accelerating accelerating downward. downward. Thanks, Thanks, gravity! gravity! Δy Δy Δx

431 Bouncing Ball getheight() ball.gety() ball.getheight()

432 A Sticky Situation The ball is below the ground, so we reverse its Δ y It's still below the ground, so we reverse its Δ y again.

433 Your Turn! Import Java 16. Your Task: Make any animation that you'd like! Be creative! What can you come up with?

434 Events

435 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.

436 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.

437 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.

438 Methods for Handling Events Define any or all of the following mouse event handlers to respond to the public void mousemoved(mouseevent public void mousedragged(mouseevent public void mousepressed(mouseevent public void mousereleased(mouseevent public void mouseclicked(mouseevent public void mouseentered(mouseevent public void mouseexited(mouseevent e) Notice that these are public void and not private void. This is important! Also notice prefix. You must also import java.awt.event.*; for the MouseEvent class.

439 A Virtual Hole Puncher

440 The Mirror Box

441

442

443 Making the Mirror Box

444 MirrorBox

445 MirrorBox

446 MirrorBox

447 (x, y) MirrorBox

448 MirrorBox (x, y) (??,??)

449 MirrorBox (x, y) (??, y)

450 MirrorBox x x (x, y) (??, y)

451 MirrorBox x x (x, y) (getwidth() - x, y)

452 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!

453 Boolean Values

454 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) {

455 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.

456 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 is not prime: it's 2 12, 3 8, and 4 6.

457 A Note about Programming Languages

458 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

459 Interacting with the Canvas

460 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 GLabel returned. GRect GOval GLine

461 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.

462 A Debris Sweeper

463 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().

464 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().

465 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().

466 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().

467 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().

468 Fields

469 A Friendly Circle Graphics Program

470 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.

471 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.

472 A Picture Reveal Game

473 RevealPuzzle

474

475

476

477

478

479

480

481

482 Sketchpad

483 Sketchpad

484 Sketchpad

485 Sketchpad

486 Clicking and Dragging

487 SuchADrag

488 SuchADrag

489 SuchADrag

490 SuchADrag

491 SuchADrag

492 SuchADrag

493 SuchADrag

494 SuchADrag

495 SuchADrag

496 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

Variables, Types, and Expressions

Variables, Types, and Expressions Variables, Types, and Expressions Announcements Karel the Robot due right now. Email: Due Sunday, January 22 at 11:59PM. Update to assignment due dates: Assignments 2 5 going out one day later. Contact

More information

Expressions, Statements, and Control Structures

Expressions, Statements, and Control Structures Expressions, Statements, and Control Structures Announcements Assignment 2 out, due next Wednesday, February 1. Explore the Java concepts we've covered and will be covering. Unleash your creative potential!

More information

Expressions and Control Statements

Expressions and Control Statements Expressions and Control Statements Recap From Last Time Variables A variable is a location where a program can store information for later use. Each variable has three pieces of information associated

More information

Introduction to Java

Introduction to Java Introduction to Java Announcements Programming Assignment #1 Out: Karel the Robot: Due Friday, January 18 at 3:15 PM. Email: Due Sunday, January 20 at 11:59PM. Section assignments given out on Tuesday;

More information

Introduction to Java

Introduction to Java Introduction to Java A Farewell to Karel Welcome to Java But First... A Brief History of Digital Computers Image credit: http://upload.wikimedia.org/wikipedia/commons/4/4e/eniac.jpg Programming in the

More information

Objects and Graphics

Objects and Graphics Objects and Graphics One Last Thought on Loops... Looping Forever while loops iterate as long as their condition evaluates to true. A loop of the form while (true) will loop forever (unless something stops

More information

Expressions and Control Statements

Expressions and Control Statements Expressions and Control Statements Announcements Programming Assignment #1 Out: Karel the Robot: Due Friday, January 18 at 3:15 PM. Email: Due Sunday, January 20 at 11:59PM. Need help? Stop by the LaIR!

More information

Programming Lecture 4

Programming Lecture 4 Five-Minute Review 1. What are classes and objects? What is a class hierarchy? 2. What is an expression? A term? 3. What is a variable declaration? 4. What is an assignment? What is precedence? 5. What

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Casual Dinner for Women in CS Next Thursday, January 24 in Gates 219 at 6:00PM. Good food, great company, and everyone is invited! RSVP through email link (sent out earlier

More information

Programming Lecture 4

Programming Lecture 4 Five-Minute Review 1. What are classes and objects? What is a class hierarchy? 2. What is an expression? A term? 3. What is a variable declaration? 4. What is an assignment? What is precedence? 5. What

More information

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1 Chapter 2 Input, Processing, and Output Fall 2016, CSUS Designing a Program Chapter 2.1 1 Algorithms They are the logic on how to do something how to compute the value of Pi how to delete a file how to

More information

Friday Four Square! Today at 4:15PM, Outside Gates

Friday Four Square! Today at 4:15PM, Outside Gates Control Structures Announcements Programming Assignment #1 due right now. Due on next Wednesday if using a late day. Email due on Sunday night. Programming Assignment #2 out today, due Wednesday, January

More information

CS 106A, Lecture 11 Graphics

CS 106A, Lecture 11 Graphics CS 106A, Lecture 11 Graphics reading: Art & Science of Java, 9.1-9.3 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All

More information

Assignment 2: Welcome to Java!

Assignment 2: Welcome to Java! CS106A Winter 2011-2012 Handout #12 January 23, 2011 Assignment 2: Welcome to Java! Based on a handout by Eric Roberts and Mehran Sahami Having helped Karel the Robot through the challenges of Assignment

More information

Programming Lecture 4

Programming Lecture 4 Five-Minute Review 1. What is a class hierarchy? 2. Which graphical coordinate system is used by Java (and most other languages)? 3. Why is a collage a good methapher for GObjects? 4. What is a CFG? What

More information

Variables Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Variables Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University Variables Chris Piech CS106A, Stanford University New Ability Write a program that calculates the tax, tip and total bill for us at a restaurant. The program should ask the user for the subtotal, and then

More information

Drawing Geometrical Objects. Graphic courtesy of Eric Roberts

Drawing Geometrical Objects. Graphic courtesy of Eric Roberts Methods Drawing Geometrical Objects Graphic courtesy of Eric Roberts Drawing Geometrical Objects Constructors new GRect( x, y, width, height) Creates a rectangle whose upper left corner is at (x, y) of

More information

Programming Lecture 2. Programming by example (Chapter 2) Hello world Patterns Classes, objects Graphical programming

Programming Lecture 2. Programming by example (Chapter 2) Hello world Patterns Classes, objects Graphical programming Five-Minute Review 1. What steps do we distinguish in solving a problem by computer? 2. What are essential properties of an algorithm? 3. What is a definition of Software Engineering? 4. What types of

More information

YEAH Hours. January , 7-8 PM Jared Wolens

YEAH Hours. January , 7-8 PM Jared Wolens YEAH Hours January 23 2017, 7-8 PM Jared Wolens YEAH Hours? Held after each assignment is released Future dates to be scheduled soon Review + Assignment Tips Plan for today: lecture review, assignment

More information

Programming via Java Subclasses

Programming via Java Subclasses Programming via Java Subclasses Every class in Java is built from another Java class. The new class is called a subclass of the other class from which it is built. A subclass inherits all the instance

More information

Solutions for Section #2

Solutions for Section #2 Chris Piech Section #2 CS 106A January 24, 2018 Solutions for Section #2 1. The Fibonacci sequence Portions of this handout by Eric Roberts and Jeremy Keeshin * File: Fibonacci.java * This program lists

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Simple Java YEAH Hours. Brahm Capoor and Vrinda Vasavada

Simple Java YEAH Hours. Brahm Capoor and Vrinda Vasavada Simple Java YEAH Hours Brahm Capoor and Vrinda Vasavada What are YEAH hours? Held soon after each assignment is released Help you to get an early start on your assignments Future dates TBA Slides will

More information

SUBCLASSES IN JAVA - II

SUBCLASSES IN JAVA - II SUBCLASSES IN JAVA - II Subclasses and variables Any instance of a class A can also be treated as an instance of a superclass of A. Thus, if B is a superclass of A, then every A object can also be treated

More information

Solutions for Section #2

Solutions for Section #2 Chris Piech Handout #12A CS 106A January 25, 2017 Solutions for Section #2 1. The Fibonacci sequence Portions of this handout by Eric Roberts and Jeremy Keeshin * File: Fibonacci.java * --------------------

More information

Assignment #2: Simple Java Programs Due: 1:15pm on Friday, April 19th

Assignment #2: Simple Java Programs Due: 1:15pm on Friday, April 19th Steve Cooper Handout #13 CS 106A April 12, 2013 Assignment #2: Simple Java Programs Due: 1:15pm on Friday, April 19th Your Early Assignment Help (YEAH) hours: time: tbd, Tues., Apr. 16th in location:tbd

More information

CS106A Review Session

CS106A Review Session CS106A Review Session Nick Troccoli This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides

More information

CS 106A, Lecture 5 Booleans and Control Flow

CS 106A, Lecture 5 Booleans and Control Flow CS 106A, Lecture 5 Booleans and Control Flow suggested reading: Java Ch. 3.4-4.6 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5

More information

Programming Lecture 4

Programming Lecture 4 Five-Minute Review 1. What is a class hierarchy? 2. Which graphical coordinate system is used by Java (and most other languages)? 3. Why is a collage a good methapher for GObjects? 4. What is a CFG? What

More information

Solutions for Section #4

Solutions for Section #4 Colin Kincaid Section #4 CS 106A July 20, 2018 Solutions for Section #4 1. Warmup: Parameters (MakeBoxes) Portions of this handout by Eric Roberts, Marty Stepp, Chris Piech, Ruchir Rastogi, and Guy Blanc

More information

CS103 Spring 2018 Mathematical Vocabulary

CS103 Spring 2018 Mathematical Vocabulary CS103 Spring 2018 Mathematical Vocabulary You keep using that word. I do not think it means what you think it means. - Inigo Montoya, from The Princess Bride Consider the humble while loop in most programming

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

Math Modeling in Java: An S-I Compartment Model

Math Modeling in Java: An S-I Compartment Model 1 Math Modeling in Java: An S-I Compartment Model Basic Concepts What is a compartment model? A compartment model is one in which a population is modeled by treating its members as if they are separated

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

Getting Familiar with ACM_JTF

Getting Familiar with ACM_JTF Getting Familiar with ACM_JTF PART1: Introduction to the JTF Packages In early 2004, the ACM created the Java Task Force (JTF) to review the Java language, APIs, and tools from the perspective of introductory

More information

Introduction to Java Unit 1. Using BlueJ to Write Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

MITOCW watch?v=0jljzrnhwoi

MITOCW watch?v=0jljzrnhwoi MITOCW watch?v=0jljzrnhwoi The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Primitive Data, Variables, and Expressions; Simple Conditional Execution Unit 2, Part 1 Primitive Data, Variables, and Expressions; Simple Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Overview of the Programming Process Analysis/Specification

More information

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology. Guide to and Hi everybody! In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology. This guide focuses on two of those symbols: and. These symbols represent concepts

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements Topic 4 Variables Once a programmer has understood the use of variables, he has understood the essence of programming -Edsger Dijkstra What we will do today Explain and look at examples of primitive data

More information

Using Eclipse and Karel

Using Eclipse and Karel Alisha Adam and Rohit Talreja CS 106A Summer 2016 Using Eclipse and Karel Based on a similar handout written by Eric Roberts, Mehran Sahami, Keith Schwarz, and Marty Stepp If you have not already installed

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

More information

YEAH 2: Simple Java! Avery Wang Jared Bitz 7/6/2018

YEAH 2: Simple Java! Avery Wang Jared Bitz 7/6/2018 YEAH 2: Simple Java! Avery Wang Jared Bitz 7/6/2018 What are YEAH Hours? Your Early Assignment Help Only for some assignments Review + Tips for an assignment Lectures are recorded, slides are posted on

More information

Formal Methods of Software Design, Eric Hehner, segment 1 page 1 out of 5

Formal Methods of Software Design, Eric Hehner, segment 1 page 1 out of 5 Formal Methods of Software Design, Eric Hehner, segment 1 page 1 out of 5 [talking head] Formal Methods of Software Engineering means the use of mathematics as an aid to writing programs. Before we can

More information

CS106A Handout 15 Winter 2015 February 4, 2015 CS106A Practice Midterm

CS106A Handout 15 Winter 2015 February 4, 2015 CS106A Practice Midterm CS106A Handout 15 Winter 2015 February 4, 2015 CS106A Practice Midterm This exam is closed-book and closed-computer but open-note. You may have a double-sided, 8.5 11 sheet of notes with you when you take

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java Chapter 3 Syntax, Errors, and Debugging Objectives Construct and use numeric and string literals. Name and use variables and constants. Create arithmetic expressions. Understand the precedence of different

More information

Slide 1 CS 170 Java Programming 1 Object-Oriented Graphics Duration: 00:00:18 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 Object-Oriented Graphics Duration: 00:00:18 Advance mode: Auto CS 170 Java Programming 1 Object-Oriented Graphics The Object-Oriented ACM Graphics Classes Slide 1 CS 170 Java Programming 1 Object-Oriented Graphics Duration: 00:00:18 Hello, Welcome to the CS 170, Java

More information

CS 106A, Lecture 25 Life After CS 106A, Part 1

CS 106A, Lecture 25 Life After CS 106A, Part 1 CS 106A, Lecture 25 Life After CS 106A, Part 1 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based

More information

Control Statements. if for while

Control Statements. if for while Control Structures Control Statements if for while Control Statements if for while This This is is called called the the initialization initialization statement statement and and is is performed performed

More information

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

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto CS 170 Java Programming 1 Working with Rows and Columns Slide 1 CS 170 Java Programming 1 Duration: 00:00:39 Create a multidimensional array with multiple brackets int[ ] d1 = new int[5]; int[ ][ ] d2;

More information

Arithmetic Expressions in C

Arithmetic Expressions in C Arithmetic Expressions in C Arithmetic Expressions consist of numeric literals, arithmetic operators, and numeric variables. They simplify to a single value, when evaluated. Here is an example of an arithmetic

More information

[ the academy_of_code] Senior Beginners

[ the academy_of_code] Senior Beginners [ the academy_of_code] Senior Beginners 1 Drawing Circles First step open Processing Open Processing by clicking on the Processing icon (that s the white P on the blue background your teacher will tell

More information

Introduction to Java

Introduction to Java Introduction to Java Announcements Programming Assignment #1 Out: Karel the Robot: Due Friday, January 20 at 3:15 PM. Email: Due Sunday, January 22 at 11:59PM. Section Assignments Posted Check online at

More information

SFPL Reference Manual

SFPL Reference Manual 1 SFPL Reference Manual By: Huang-Hsu Chen (hc2237) Xiao Song Lu(xl2144) Natasha Nezhdanova(nin2001) Ling Zhu(lz2153) 2 1. Lexical Conventions 1.1 Tokens There are six classes of tokes: identifiers, keywords,

More information

CS 106A Midterm Review. Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017

CS 106A Midterm Review. Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017 + CS 106A Midterm Review Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017 Details n Only the textbook is allowed n n n The Art and Science of Java Karel Course Reader You will

More information

Programming via Java Defining classes

Programming via Java Defining classes Programming via Java Defining classes Our programs so far have used classes, like Turtle and GOval, which were written by other people. In writing larger programs, we often find that another class would

More information

Class #1. introduction, functions, variables, conditionals

Class #1. introduction, functions, variables, conditionals Class #1 introduction, functions, variables, conditionals what is processing hello world tour of the grounds functions,expressions, statements console/debugging drawing data types and variables decisions

More information

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Building Java Programs. Chapter 2: Primitive Data and Definite Loops Building Java Programs Chapter 2: Primitive Data and Definite Loops Copyright 2008 2006 by Pearson Education 1 Lecture outline data concepts Primitive types: int, double, char (for now) Expressions: operators,

More information

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators 1 Professor: Sana Odeh odeh@courant.nyu.edu Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators Review What s wrong with this line of code? print( He said Hello ) What s wrong with

More information

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

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto CS 170 Java Programming 1 Expressions Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 What is an expression? Expression Vocabulary Any combination of operators and operands which, when

More information

9/1/2015. Chapter 2 Using Objects. Objects and Classes. Using Objects. Using Objects. Using Objects. Classes. Ch. 1/2 Lab Time

9/1/2015. Chapter 2 Using Objects. Objects and Classes. Using Objects. Using Objects. Using Objects. Classes. Ch. 1/2 Lab Time Chapter 2 Using Objects The Plan For Today Chapter 1 Quiz Results Chapter 2 2.1: Objects and Classes 2.2: Variables 2.3: Calling Methods 2.4: Constructing Objects Ch. 1/2 Lab Time Ch. 1 Assignment Due

More information

Assignment #1: /Survey and Karel the Robot Karel problems due: 1:30pm on Friday, October 7th

Assignment #1:  /Survey and Karel the Robot Karel problems due: 1:30pm on Friday, October 7th Mehran Sahami Handout #7 CS 06A September 8, 06 Assignment #: Email/Survey and Karel the Robot Karel problems due: :0pm on Friday, October 7th Email and online survey due: :9pm on Sunday, October 9th Part

More information

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

More information

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to A PROGRAM IS A SEQUENCE of instructions that a computer can execute to perform some task. A simple enough idea, but for the computer to make any use of the instructions, they must be written in a form

More information

Mehran Sahami Handout #7 CS 106A September 24, 2014

Mehran Sahami Handout #7 CS 106A September 24, 2014 Mehran Sahami Handout #7 CS 06A September, 0 Assignment #: Email/Survey and Karel the Robot Karel problems due: :pm on Friday, October rd Email and online survey due: :9pm on Sunday, October th Part I

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Express Yourself. The Great Divide

Express Yourself. The Great Divide CS 170 Java Programming 1 Numbers Working with Integers and Real Numbers Open Microsoft Word and create a new document Save the file as LastFirst_ic07.doc Replace LastFirst with your actual name Put your

More information

Slide 1 CS 170 Java Programming 1

Slide 1 CS 170 Java Programming 1 CS 170 Java Programming 1 Objects and Methods Performing Actions and Using Object Methods Slide 1 CS 170 Java Programming 1 Objects and Methods Duration: 00:01:14 Hi Folks. This is the CS 170, Java Programming

More information

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 1 Lecture 2: Static Methods reading: 1.4-1.5 (Slides adapted from Stuart Reges, Hélène Martin, and Marty Stepp) 2 Recall: structure, syntax class: a program public class

More information

Fundamentals of Programming Session 4

Fundamentals of Programming Session 4 Fundamentals of Programming Session 4 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2011 These slides are created using Deitel s slides, ( 1992-2010 by Pearson Education, Inc).

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

More information

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Assignment 1: grid. Due November 20, 11:59 PM Introduction CS106L Fall 2008 Handout #19 November 5, 2008 Assignment 1: grid Due November 20, 11:59 PM Introduction The STL container classes encompass a wide selection of associative and sequence containers. However,

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

Programming Lecture 2. Programming by example (Chapter 2) Hello world Patterns Classes, objects Graphical programming

Programming Lecture 2. Programming by example (Chapter 2) Hello world Patterns Classes, objects Graphical programming Five-Minute Review 1. What steps do we distinguish in solving a problem by computer? 2. What are essential properties of an algorithm? 3. What is a definition of Software Engineering? 4. What types of

More information

Assignment #1: and Karel the Robot Karel problems due: 3:15pm on Friday, October 4th due: 11:59pm on Sunday, October 6th

Assignment #1:  and Karel the Robot Karel problems due: 3:15pm on Friday, October 4th  due: 11:59pm on Sunday, October 6th Mehran Sahami Handout #7 CS 06A September, 0 Assignment #: Email and Karel the Robot Karel problems due: :pm on Friday, October th Email due: :9pm on Sunday, October 6th Part I Email Based on a handout

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

CS102: Variables and Expressions

CS102: Variables and Expressions CS102: Variables and Expressions The topic of variables is one of the most important in C or any other high-level programming language. We will start with a simple example: int x; printf("the value of

More information

MITOCW watch?v=ytpjdnlu9ug

MITOCW watch?v=ytpjdnlu9ug MITOCW watch?v=ytpjdnlu9ug The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality, educational resources for free.

More information

Chapter 1 Introduction to Java

Chapter 1 Introduction to Java Chapter 1 Introduction to Java Lesson page 0-1. Introduction to Livetexts Question 1. A livetext is a text that relies not only on the printed word but also on graphics, animation, audio, the computer,

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

Java Programming. Computer Science 112 Class 2

Java Programming. Computer Science 112 Class 2 Java Programming Computer Science 112 Class 2 The first assignment It is extra credit (5/0) Mostly a test of your determination. I gave points for trying. println(" * * *"); // etc print(" * "); print(number);

More information

CS 106A, Lecture 27 Final Exam Review 1

CS 106A, Lecture 27 Final Exam Review 1 CS 106A, Lecture 27 Final Exam Review 1 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on

More information

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG 1 Notice Reading Assignment Chapter 1: Introduction to Java Programming Homework 1 It is due this coming Sunday

More information

Hello, World and Variables

Hello, World and Variables Hello, World and Variables Hello, World! The most basic program in any language (Python included) is often considered to be the Hello, world! statement. As it s name would suggest, the program simply returns

More information

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors First Program Compilation and Execution Simplifying Fractions Loops If Statements Variables Operations Using Functions Errors C++ programs consist of a series of instructions written in using the C++ syntax

More information