30
Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison, Thibault University of Pennsylvania 13 February 2008

Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

  • View
    228

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Intro to Computer Science Class #4

If Statements, While Loops and For Loops

Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj, Isaiah, Allison, Thibault

University of Pennsylvania

13 February 2008

Page 2: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Today’s Agenda

• Discussion/Demo (Reaction paper, BetterBot and Extras)– .hist files– Comments and Javadocs

• Review• If Statements• Boolean Expressions• While Loops• For Loops

• LoopingBot

Page 3: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Discussion/Demo

Let’s talk about the reaction paper and demo BetterBot and BetterBot Extras.

Page 4: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

What We Covered in the Demo .hist files

• A convenient way to test your code -- interaction history files.

• Two ways to make a .hist file:– 1) After running through the interactions once, Tools -> Save

Interactions History as Script – 2) Create a new file in DrJava (New button in top left).

• Save file as name.hist (and change to Files of Type: All Files). • Put //DrJava saved history v2 at the top of the file and //End of Interaction//

at the end of each statement you type.

• To run a .hist file– Tools->Load Interactions History As Script. – Four buttons will appear on the right side of the Interactions Pane.– Hit the Next and Execute buttons one after the other. – (check out resources page)

Page 5: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

What We Covered in the Demo Comments and Javadocs

• Comments make code more readable to humans• They are ignored by the computer/compiler/Java

• // A single line comment starts with two forward slashes

• /* A multi-line comment starts with a forward slash and star.* People usually put a star at the beginning of* other lines like this. The comment ends with star slash.*/

• /* You can also do a single line comment like this. */

• /** This is a “javadoc” comment. Note the extra star.* These comments are used to generate a separate* users manual on a web page (called the “javadoc”).*/

Page 6: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder: What Are These and How Are They Used?

• class Athlete {String name ;String sport; int salary;int daysInjured; String popularity;

Athlete(String n, String s) {name = n;sport = s;salary = 0;daysInjured = 0; popularity = “average”;

}

void negotiateContract(int newSalary) {salary = newSalary;

}

void party() {daysInjured = daysInjured + 10;

}

void complain() {popularity = “low”;

}

void retire() { salary = 0;popularity = “high”;

}

void printStates() {System.out.println(“name: “ + name + “, sport: “ + sport + “, salary: “ + salary + “, daysInjured: “ + daysInjured + “, popularity”);

}}

Page 7: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder: What Are These and How Are They Used?

• class Athlete {String name ;String sport; int salary;int daysInjured; String popularity;

Athlete(String n, String s) {name = n;sport = s;salary = 0;daysInjured = 0; popularity = “average”;

}

void negotiateContract(int newSalary) {salary = newSalary;

}

void party() {daysInjured = daysInjured + 10;

}

void complain() {popularity = “low”;

}

void retire() { salary = 0;popularity = “high”;

}

void printStates() {System.out.println(“name: “ + name + “, sport: “ + sport + “, salary: “ + salary + “, daysInjured: “ + daysInjured + “, popularity”);

}}

instance variables (hold the state)

methods

•modify the instance variables (behaviors changing the state)

•return the instance variables (tell us about the state)

class (object blueprint)

constructor.

•Creates the object

•Sets the starting state

Page 8: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder:Variables

• Purpose? Store and retrieve a value in/from memory

• Must be declared once before being used, why?– Indicates how much space in memory is needed to hold it and which operations are allowed

to be performed on it.

• How do we declare? type_of_variable variable_name; • How do we assign? variable_name = data_value;

• 2 types of data (type_of_variable):– Primitive: int, double char, boolean

• Acted on by symbolic operators (+,-,/,-,==,>,<, etc).– Non-Primitive: String and any class we or Java create.

• Acted on by methods [variable_name.method_name(parameters)]• Data must be created first to be assigned: variable_name = new constructor(parameter_list);

• Rules for naming variables:– Should be descriptive!– Can’t use keywords – Case-sensitive (hello ≠ Hello)– Must begin with: A letter, followed by any combo of letters, numbers, $ and _– No spaces allowed: write the 1st word lowercase, all other words with first letter capitalized

x

y

5

10

Page 9: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder:Variables

• Purpose? Store and retrieve a value in/from memory

• Must be declared once before being used, why?– Indicates how much space in memory is needed to hold it and which operations are allowed

to be performed on it.

• How do we declare? type_of_variable variable_name; • How do we assign? variable_name = data_value;

• 2 types of data (type_of_variable):– Primitive: int, double char, boolean

• Acted on by symbolic operators (+,-,/,-,==,>,<, etc).– Non-Primitive: String and any class we or Java create.

• Acted on by methods [variable_name.method_name(parameters)]• Data must be created first to be assigned: variable_name = new constructor(parameter_list);

• Rules for naming variables:– Should be descriptive!– Can’t use keywords – Case-sensitive (hello ≠ Hello)– Must begin with: A letter, followed by any combo of letters, numbers, $ and _– No spaces allowed: write the 1st word lowercase, all other words with first letter capitalized

x

y

5

10

Page 10: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder:Three Ways to Use Variables

• class Athlete {String name ;String sport; int salary;int daysInjured; String popularity;

Athlete(String n, String s) {name = n;sport = s;salary = 0;daysInjured = 0; popularity = “average”;

}

void negotiateContract(int newSalary) {int bargain = 2;salary = newSalary/bargain;

}...//the rest of the methods

}

Page 11: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder:Three Ways to Use Variables

• class Athlete {String name ;String sport; int salary;int daysInjured; String popularity;

Athlete(String n, String s) {name = n;sport = s;salary = 0;daysInjured = 0; popularity = “average”;

}

void negotiateContract(int newSalary) {int bargain = 2;salary = newSalary/bargain;

}...//the rest of the methods

}

Instance variables

•Stores state of each object

•Declared at top of class

•Scope: Accessible to entire object.

Parameters

•Values passed into methods

•Scope: Accessible to entire method

Local variables

•Stores temporary state of a method

•Declared at top of method

•Scope: Accessible to entire method

Page 12: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder: Methods

• modifier return_type method_name(parameter_list) {method_body

}

• modifier:– What can “see” it, for now, assume public.

• return_type:– What values can this take? Any primitive or non-primitive type + void.– What’s it specifying? Data type of the value returned by the method, void if

nothing.• method_name:

– What are the rules? Same as for variable names + generally contains a verb • parameter_list:

– What does it do? Pass data to the method -- Can be empty or contain a list. • method_body:

– Includes? Declaration of local variables, manipulation of variables (instance, local or parameters), return statement (returns data of type return_type).

public void party() {

daysInjured = daysInjured + 10;

}

Page 13: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder: Methods

• modifier return_type method_name(parameter_list) {method_body

}

• modifier:– What can “see” it, for now, assume public.

• return_type:– What values can this take? Any primitive or non-primitive type + void.– What’s it specifying? Data type of the value returned by the method, void if

nothing.• method_name:

– What are the rules? Same as for variable names + generally contains a verb • parameter_list:

– What does it do? Pass data to the method -- Can be empty or contain a list. • method_body:

– Includes? Declaration of local variables, manipulation of variables (instance, local or parameters), return statement (returns data of type return_type).

public void party() {

daysInjured = daysInjured + 10;

}

Page 14: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder: Snapshot of a modified Athlete class

• public class Athlete {int salary;….

public void negotiateContract ( int newSalary ) {int bargain = 2;salary = newSalary/bargain;

}

public int getSalary ( ) {return salary;

}

...//the rest of the methods

}

Page 15: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder: Snapshot of a modified Athlete class

• public class Athlete {int salary;….

public void negotiateContract ( int newSalary ) {int bargain = 2;salary = newSalary/bargain;

}

public int getSalary ( ) {return salary;

}

...//the rest of the methods

}

method_body

parameter_list method_name return_type (void so no return statement)

modifier

parameter_list (empty)method_name modifier

return_type

method_body (returns an int)

Page 16: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder: The Constructor

• modifier class_name(parameter_list) {constructor_body

}

• Creates the object from the class “blueprint”.

• Looks like a method, with some differences:– No return_type.– Its name is always the same as the class.

• Sets up the initial state.

• When is it used?– Variable declaration and assignment for non-primitive types:

type_of_variable variable_name = new constructor(parameter_list);

ex. Athlete a1 = new Athlete(“Ryan”, “Baseball Player”);– Any class you create becomes a non-primitive type

public Athlete(String n, String s) { name = n; sport = s; salary = 0; daysInjured = 0; popularity = “average”;}

Page 17: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder: The Constructor

• modifier class_name(parameter_list) {constructor_body

}

• Creates the object from the class “blueprint”.

• Looks like a method, with some differences:– No return_type.– Its name is always the same as the class.

• Sets up the initial state.

• When is it used?– Variable declaration and assignment for non-primitive types:

type_of_variable variable_name = new constructor(parameter_list);

ex. Athlete a1 = new Athlete(“Ryan”, “Baseball Player”);– Any class you create becomes a non-primitive type

public Athlete(String n, String s) { name = n; sport = s; salary = 0; daysInjured = 0; popularity = “average”;}

Page 18: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder:

Introduction to Inheritance • modifier class subclass_name extends superclass_name {

class_body}

• What is the purpose of inheritance?– Subclass inherits all the functionality of the superclass while keeping it

intact.– Maybe can’t get to the code to modify it, like with the Bot class– Copy and Pase is a waste of time and space (memory).

• Constructor of superclass not inherited, so must call super(parameters); within the subclass constructor.

• Most common way this is done is : Object class– All classes extend the object class public class BetterBot extends Bot {

public BetterBot(BotWorld world){ super(world);

} //additional methods}

Page 19: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Reminder:

Introduction to Inheritance • modifier class subclass_name extends superclass_name {

class_body}

• What is the purpose of inheritance?– Subclass inherits all the functionality of the superclass while keeping it

intact.– Maybe can’t get to the code to modify it, like with the Bot class– Copy and Pase is a waste of time and space (memory).

• Constructor of superclass not inherited, so must call super(parameters); within the subclass constructor.

• Most common way this is done is : Object class– All classes extend the object class public class BetterBot extends Bot {

public BetterBot(BotWorld world){ super(world);

} //additional methods}

Page 20: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Control Flow

• What happens to our eatAllDots method if there was a different dot configuration?

• Right now our programs always execute the statements in a method in the order that we write (from top to bottom). We need a way to let our programs make a “decision”.

• if statements, while loops, for loops– These all allow the program to “decide” whether or not

to execute sections of code.

Page 21: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

if Statements• Tells your program to only execute a certain section

of code if a boolean expression evaluates to true.

• If the first boolean expression is false, then check the second boolean expression and execute the 2nd section of code if that expression evaluates to true.

– You can have 0-unlimited number of “ else if ” expressions.

• If none of the boolean expressions evaluate to true, then execute the body of the “else”.

– You can have 0 or 1 “else”

• The if statement must always start with an “if”, can have an unlimited number of “else if”s in the middle, and if there is an “else” it must come at the end.

if ( boolean_expression ) { body_of_statement}

if ( boolean_expression1 ) { body_of_statement1}else if ( boolean_expression2 ) { body_of_statement2}

if ( boolean_expression1 ) { body_of_statement1}else if ( boolean_expression2 ) { body_of_statement2}else { body_of_statement3}

Page 22: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Boolean Expressions• true, false

• || -- “or” – if a or b is true, then the expression is true. If not, the expression is false.

• && -- “and”– If a and b are true, then the expression is true. If not, the expression is false.

• ! = “not”– If a is true then the expression is false. If not, the expression is true.

• == -- is equal to• != -- is not equal to• < -- less than• <= -- less than or equal• > -- greater than• >= -- greater than or equal

• Methods that return booleans

boolean a = true;

boolean b = false;

a||b a&&b

a||a a&&a

b||a b&&a

b||b b&&b

!a !b

Page 23: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Boolean Expressions• true, false

• || -- “or” – if a or b is true, then the expression is true. If not, the expression is false.

• && -- “and”– If a and b are true, then the expression is true. If not, the expression is false.

• ! = “not”– If a is true then the expression is false. If not, the expression is true.

• == -- is equal to• != -- is not equal to• < -- less than• <= -- less than or equal• > -- greater than• >= -- greater than or equal

• Methods that return booleans

boolean a = true;

boolean b = false;

a||b true a&&b false

a||a true a&&a true

b||a true b&&a false

b||b false b&&b false

!a false !b true

Page 24: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Boolean Expressions• What would these evaluate to?

• boolean isTired=true;boolean isHungry=false;int ageOfBob = 15;double heightOfBob = 60.5

• isTired || isHungry• isTired && isHungry• ageOfBob == heightOfBob• ageOfBob != heightOfBob• ageOfBob <= heightOfBob• !( (heightOfBob >= ageOfBob) || (isHungry) )

Page 25: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Boolean Expressions• What would these evaluate to?

• boolean isTired=true;boolean isHungry=false;int ageOfBob = 15;double heightOfBob = 60.5

• isTired || isHungry true• isTired && isHungry false• ageOfBob == heightOfBob false• ageOfBob != heightOfBob true• ageOfBob <= heightOfBob true• !( (heightOfBob >= ageOfBob) || (isHungry) ) false

– Very important to put parentheses around your expressions to make sure the computer evaluates them the way you want them evaluated

Page 26: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Back to if statements

• What are these if statements deciding and when do you execute each body of the statements:

• if(likesTV && isSaturday) watchTV();else

goToSchool();

• if(myAge > yourAge) return true;else if (myAge == yourAge)

return calculateExactAgeDifference();else

return false;

Page 27: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

while Loops• while (boolean_expression) {

body_of_loop;}

• Similar to if statement, except, instead of executing the body of the loop once and continuing, it loops through the body until the boolean expression becomes false.

• Examples:• boolean wantsToRideCoaster = true;

while (wantsToRideCoaster) {//rideRollerCoaster() returns true if, after the ride, she wants to ride again.

wantsToRideCoaster = rideRollerCoaster();}

• int numLoops = 0;while (numLoops<10) {

doSomething();numLoops = numLoops+1;

}• You will do something like this a lot (run a loop exactly n times), so we need a more

efficient way to do that (while loops are still good for the 1st example though).

Page 28: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

for Loops• for (initialization; boolean_expression; increment) {

body_of_loop;}

• initialization: executed once, before loop begins, initializes variable being checked. – Scope: Variables declared during this step is anywhere in the for loops. So any code

outside of the for loop cannot use it.• boolean expression: Like while loop: tested before each loop iteration and, if false,

stops executing loop body.• increment: changes value of variable after each iteration through the loop.

– i++ means i = i+1;– Doesn’t have to increment (just what it normally is). Could decrement (i-- means i=i-1) or

any mathematical operation.

• Examples:• Remember: int numLoops = 0;

while (numLoops<10) {doSomething();numLoops = numLoops+1;

}

Now: for (int i=0; i<10; i++) {

doSomething(); }

Page 29: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Now…

• Write down something you were confused about from class and a short explanation about what confused you (1-3 sentences). (Submit using the submission link).

• LoopingBothttps://www.seas.upenn.edu/~eas285/forSLAStudents/lectures/lecture4_IfStatementsLoopsComments/modifiedloopingbot/assignment

Page 30: Intro to Computer Science Class #4 If Statements, While Loops and For Loops Instructor: Ms. Catherine Stocker Teaching Assistants: Alex, Katie, Siraaj,

Later…

• Finish LoopingBot. Comment your methods in proper javadoc style.

• Ask questions on the bulletin board.

• Submit using the link on the webpage