CS 106A, Lecture 5 - Stanford University= does not equal 3.2 != 2.5 true < less than 10 < 5...

Preview:

Citation preview

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

CS106A,Lecture5Booleans,ControlFlowandScope

suggestedreading:JavaCh.3.4-4.6

2

Plan For Today•Announcements•Recap:Java,VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

3

Plan For Today•Announcements•Recap:Java,VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

4

Plan For Today•Announcements•Recap:Java,VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

5

Java

Karel Program Graphics ProgramConsole Program

SuperKarel Program

Program

6

Console Programsimport acm.program.*;

public class Name extends ConsoleProgram {public void run() {

statements;}

}

• UnlikeKarel,manyprogramsproducetheirbehavior astext.• console:Textboxintowhichthebehavior isdisplayed.

– output: Messagesdisplayedbytheprogram.– input: Datareadbytheprogramthattheusertypes.

7

println• Astatementthatprintsalineofoutputontheconsole,andgoestothenextline.– pronounced"print-linn"

• Twowaystouseprintln :

• println("text");• Printsthegivenmessageasoutput,andgoestothenextline.• Amessageiscalledastring;itstarts/endswitha" quotecharacter.• Thequotesdonotappearintheoutput.• Astringmaynotcontaina" character.

• println();Printsablanklineofoutput.

8

printpublic class HelloWorld extends ConsoleProgram {

public void run() {print("Hello, ");print("world!");

}}

Same as println, but does not go to the next line.

9

Expressions• Youcancombineliteralsorvariablestogetherintoexpressionsusingbinaryoperators:

AdditionSubtraction

*/ Division% Remainder

+–

Multiplication

10

Precedence• precedence:Orderinwhichoperatorsareevaluated.

– Generallyoperatorsevaluateleft-to-right.1 - 2 - 3 is(1 - 2) - 3 whichis-4

– But* / % haveahigherlevelofprecedencethan+ -1 + 3 * 4 is13

6 + 8 / 2 * 36 + 4 * 36 + 12 is18

– Parenthesescanalterorderofevaluation,butspacingdoesnot:(1 + 3) * 4 is161+3 * 4-2 is11

11

Type Interactions

int and int results in an intdouble and double results in a double

int and double results in a double

* The general rule is: operations always return the most expressive type

String and int results in a String

etc.

12

Integer division• Whenwedivideintegers,thequotientisalsoaninteger.

14 / 4 is3,not3.5 .(JavaALWAYSroundsdown.)

3 4 524 ) 14 10 ) 45 27 ) 1425

12 40 1352 5 75

5421

• Moreexamples:– 32 / 5 is6– 84 / 10 is8– 156 / 100 is1

– Dividingby0 causesanerrorwhenyourprogramruns.

13

Practice

•1/2 0 •1.0/2 0.5•1+2/3 1•"abc"+(4+2) "abc6"•"abc"+4 +2"abc42"

14

Making a new Variable

int myVariable;

type name

15

Variable Types

int – an integer number

double – a decimal number

16

Assignment

myVariable = 2;

Existing variable name value

17

Assignment• assignment:Storesavalueintoavariable.

– Thevaluecanbeanexpression;thevariablestoresitsresult.

• Syntax:

name = expression;

int zipcode;zipcode = 90210;

double myGPA;myGPA = 1.0 + 2.25;

zipcode 90210

myGPA 3.25

18

Declare / initialize• Avariablecanbedeclared/initializedinonestatement.

– Thisisprobablythemostcommonlyuseddeclarationsyntax.

• Syntax:

type name = expression;

double tempF = 98.6;

int x = (12 / 2) + 3;x 9

tempF 98.6

19

Using Variables

// Asks the user for an integer by// displaying the given message// and stores it in the variable ’a’int a = readInt(message);

// Asks the user for a double by// displaying the given message and// stores it in the variable ’b’double b = readDouble(message);

20

Practice: Receipt Program• WewroteaConsoleProgram calledReceipt thatcalculatesthetax,tipandtotalbillforusatarestaurant.

• Theprogramaskstheuserforthesubtotal,andthencalculateandprintoutthetax,tipandtotal.

21

Plan For Today•Announcements•Recap:VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

22

Shorthand OperatorsShorthand Equivalentlongerversionvariable += value; variable = variable + value;variable -= value; variable = variable - value;variable *= value; variable = variable * value;variable /= value; variable = variable / value;variable %= value; variable = variable % value;

variable++; variable = variable + 1;variable--; variable = variable – 1;

x += 3; // x = x + 3;number *= 2; // number = number * 2;x++; // x = x + 1;

23

Constants• constant:Avariablethatcannotbechangedafteritisinitialized.Declaredatthetopofyourclass,outsideoftherun()method.Canbeusedanywhereinthatclass.

• Betterstyle– caneasilychangetheirvaluesinyourcode,andtheyareeasiertoreadinyourcode.

• Syntax:private static final type name = value;

– nameisusuallyinALL_UPPER_CASE

– Examples:private static final int DAYS_IN_WEEK = 7;private static final double INTEREST_RATE = 3.5;private static final int SSN = 658234569;

24

Receipt Program - Beforepublic class Receipt extends ConsoleProgram {public void run() {double subtotal = readDouble(”Meal cost? $”);double tax = subtotal * 0.08;double tip = subtotal * 0.20;double total = subtotal + tax + tip;

println("Tax : $” + tax);println("Tip: $” + tip);println(”Total: $" + total);

}}

25

Receipt Program – Afterpublic class Receipt extends ConsoleProgram {private static final double TAX_RATE = 0.08;private static final double TIP_RATE = 0.2;

public void run() {double subtotal = readDouble(”Meal cost? $”);double tax = subtotal * TAX_RATE;double tip = subtotal * TIP_RATE;double total = subtotal + tax + tip;

println("Tax : $” + tax);println("Tip: $” + tip);println(”Total: $" + total);

}}

26

Plan For Today•Announcements•Recap:VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

27

If/Else in Karelif (condition) {

statement;statement;...

} else {statement;statement;...

}

Runsthefirstgroupofstatementsifcondition istrue;otherwise,runsthesecondgroupofstatements.

28

While Loops in Karelwhile (condition) {

statement;statement;...

}

Repeatsthestatementsinthebodyuntilcondition isnolongertrue.Eachtime,Karelexecutesallstatements,andthen checksthecondition.

29

Conditions in Karel

while(frontIsClear()) {body

}

if(beepersPresent()) {body

}

30

Conditions in Java

while(condition) {body

}

if(condition) {body

}

Theconditionshouldbea“boolean”whichiseithertrue orfalse

31

Booleans

1<2

32

Booleans

1<2

true

33

Relational Operators

Operator Meaning Example Value== equals 1 + 1 == 2 true!= doesnotequal 3.2 != 2.5 true< lessthan 10 < 5 false> greaterthan 10 > 5 true<= lessthanorequalto 126 <= 100 false>= greaterthanorequalto 5.0 >= 5.0 true

* All have equal precedence

34

Relational Operators

Operator Meaning Example Value== equals 1 + 1 == 2 true!= doesnotequal 3.2 != 2.5 true< lessthan 10 < 5 false> greaterthan 10 > 5 true<= lessthanorequalto 126 <= 100 false>= greaterthanorequalto 5.0 >= 5.0 true

* All have equal precedence

35

Relational Operatorsif (1 < 2) {

println("1 is less than 2!");}

int num = readInt("Enter a number: ");if (num == 0) {

println("That number is 0!");} else {

println("That number is not 0.");}

36

Practice: Sentinel Loops• sentinel:Avaluethatsignalstheendofuserinput.

– sentinelloop:Repeatsuntilasentinelvalueisseen.

• Example:Writeaprogramthatpromptstheuserfornumbersuntiltheusertypes-1,thenoutputthesumofthenumbers.– Inthiscase,-1isthesentinelvalue.

Type a number: 10Type a number: 20Type a number: 30Type a number: -1Sum is 60

37

Practice: Sentinel Loops// fencepost problem!// ask for number - post// add number to sum - fence

int sum = 0;int num = readInt("Enter a number: ");while (num != -1) {

sum += num;num = readInt("Enter a number: ");

}println("Sum is " + sum);

38

Practice: Sentinel Loops// Solution #2 (ok, but #1 is better)// harder to see loop end condition here

int sum = 0;while (true) {

int num = readInt("Enter a number: ");if (num == -1) {

break; // immediately exits loop}sum += num;

}println("Sum is " + sum);

39

Compound Expressions

Operator Description Example Result! not !(2 == 3) true&& and (2 == 3) && (-1 < 5) false|| or (2 == 3) || (-1 < 5) true

Cannot "chain" tests as in algebra; use && or || instead

// assume x is 15 // correct version2 <= x <= 10 2 <= x && x <= 10true <= 10 true && falseError! false

In order of precedence:

40

Precedence MadnessPrecedence:arithmetic>relational>logical

5 * 7 >= 3 + 5 * (7 – 1) && 7 <= 115 * 7 >= 3 + 5 * 6 && 7 <= 1135 >= 3 + 30 && 7 <= 1135 >= 33 && 7 <= 11true && truetrue

41

Boolean Variables// Store expressions that evaluate to true/falseboolean x = 1 < 2; // trueboolean y = 5.0 == 4.0; // false

42

Boolean Variables// Store expressions that evaluate to true/falseboolean x = 1 < 2; // trueboolean y = 5.0 == 4.0; // false

// Directly set to true/falseboolean isFamilyVisiting = true;boolean isRaining = false;

43

Boolean Variables// Store expressions that evaluate to true/falseboolean x = 1 < 2; // trueboolean y = 5.0 == 4.0; // false

// Directly set to true/falseboolean isFamilyVisiting = true;boolean isRaining = false;

// Ask the user a true/false (yes/no) questionboolean playAgain = readBoolean("Play again?”, "y", "n");if (playAgain) {...

44

Practice: GuessMyNumber• Let’swriteaprogramcalledGuessMyNumber thatpromptstheuserforanumberuntiltheyguessoursecretnumber.

• Ifaguessisincorrect,theprogramshouldprovideahint;specifically,whethertheguessistoohighortoolow.

45

Summary: Conditions

while(condition) {body

}

if(condition) {body

}

Theconditionshouldbeaboolean whichiseithertrue orfalse

46

If/Else If/Elseif (condition1) {

...} else if (condition2) { // NEW

...} else {

...}

Runsthefirstgroupofstatementsifcondition1 istrue;otherwise,runsthesecondgroupofstatementsifcondition2 istrue;otherwise,runsthethirdgroupofstatements.

Youcanhavemultipleelseifclausestogether.

47

If/Else If/Elseint num = readInt("Enter a number: ");if (num > 0) {

println("Your number is positive");} else if (num < 0) {

println("Your number is negative");} else {

println("Your number is 0");}

48

Plan For Today•Announcements•Recap:VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

49

For Loops in Karelfor (int i = 0; i < max; i++) {

statement;statement;...

}

Repeatsthestatementsinthebodymax times.

50

For Loops in Java

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

Repeats the loop if this condition

passes

51

For Loops in Java

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loop Redux

52

For Loops in Java

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loop Redux

i 0

53

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 0

54

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 0

I love CS 106A!

55

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 0

I love CS 106A!

56

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 1

I love CS 106A!

57

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 1

I love CS 106A!

58

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 1

I love CS 106A!

I love CS 106A!

59

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 2

I love CS 106A!

I love CS 106A!

60

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 2

I love CS 106A!

I love CS 106A!

61

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 2

I love CS 106A!

I love CS 106A!

I love CS 106A!

62

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 3

I love CS 106A!

I love CS 106A!

I love CS 106A!

63

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

i 3

I love CS 106A!

I love CS 106A!

I love CS 106A!

64

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

I love CS 106A!

I love CS 106A!

I love CS 106A!

65

for (int i = 0; i < 3; i++) {println("I love CS 106A!");

}

For Loops in Java

For Loop Redux

I love CS 106A!

I love CS 106A!

I love CS 106A!

66

Using the For Loop Variable

// prints the first 100 even numbersfor(int i = 0; i < 100; i++) {

println(i * 2);}

67

Using the For Loop Variable// Launch countdownfor(int i = 10; i >= 1; i--) {

println(i * 2);}println("Blast off!");

1098…Blast off!

Output:

68

Using the For Loop Variable

// Adds up the first 100 numbersint sum = 0;for(int i = 0; i < 100; i++) {

sum += i;}println("The sum is " + sum);

69

Recap•Announcements•Recap:VariablesandExpressions•Aside:ShorthandOperators+Constants•RevisitingControlFlow–IfandWhile–For

Nexttime:Morecontrolflow,methodsinJava

Recommended