cs106a review session - stanford university...event-driven programming let’s write a program like...

80
CS106A Review Session Saturday Feb. 11, 2017 Maria Yang 1

Upload: others

Post on 07-Sep-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

CS106A Review Session

Saturday Feb. 11, 2017Maria Yang

1

Page 2: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Topic List•Karel• Javaconstructs•Graphics+Animation•Memory (Pass-by-referencevs.passbyvalue)• Event-drivenprogramming•CharactersandStrings

2

Page 3: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Karel

3

Page 4: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Karel• Tips:• Pseudocodefirst• Decomposetheproblem•Mightbelimitationsonconstructs• E.g.noJavafeatures(variables,break,etc.)

4

Page 5: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Trick-or-Treat Karel

5

Karel Needs Love

Page 6: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Karelisinaworldwithwalkwaystohousesthathavevalentines.Karelshouldgotoeveryhouseinorder,goupthewalkwayandtakeallthevalentines(beepers).Housewalkwayscanbeanydistanceapart,andhaveguidewallsontheleftandrightuptothevalentine.

6

Karel Needs Love

Page 7: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

7

Demo: Karel Needs Love

Page 8: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Loop:- Gotonexthouse- GetValentines

8

Gotonexthouse:- movealongleftwall

GetValentines:- traversewalkway- takevalentine- traversewalkway

Karel Needs Love

Page 9: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

public void run() {while (frontIsClear()) {

goToNextHouse();getValentines();if (frontIsClear()) {

move();}

}}

9

Karel Needs Love

Page 10: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

private void goToNextHouse() {while (leftIsBlocked()) {

move();}

}

10

Karel Needs Love

Page 11: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

private void getValentines() {turnLeft();traverseWalkway();takeValentine();turnAround();traverseWalkway();turnLeft();

}

11

Karel Needs Love

Page 12: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

private void traverseWalkway() {move();while (leftIsBlocked() && rightIsBlocked()) {

move();}

}

12

Karel Needs Love

Page 13: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

private void takeValentine() {while (beepersPresent()) {

pickBeeper();}

}

13

Karel Needs Love

Page 14: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Java Constructs

14

Page 15: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Variabletypes:primitives(int,double,…)+objects(GRect,Goval,…)•Controlstatements:if,while,for,switch•Whatiseachusefulfor?

•Methods

15

Java Constructs

Page 16: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Variabletypes:primitives(int,double,…)+objects(GRect,Goval,…)•Controlstatements:if,while,for,switch•Whatiseachusefulfor?

•Methods

16

Java Constructs

Page 17: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•ReadinuserinputuntilyouhittheSENTINEL• Iteratethroughastring•MoveKareltoawall

17

WHILEFORWHILE

For or While?

Page 18: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Variabletypes:primitives(int,double,…)+objects(GRect,Goval,…)•Controlstatements:if,while,for,switch•Whatiseachusefulfor?

•Methods

18

Java Constructs

Page 19: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Amethodisaroutineofinstructionsthatmaytakesomeinputandgivebacksomeoutput.

19

MethodParameters Returnvalue

Java Constructs - Methods

Page 20: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

public void run() {println(“Hypotenuse of 3 and 4 is: “);println(hypotenuse(3.0, 4.0));

}

private double hypotenuse(double a, double b) {return Math.sqrt(a*a + b*b);

}

20

Java Constructs - Methods

Page 21: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Parameters arehowthecaller givesinformationtothecallee.Areturnvalueishowthecallee givesinformationbacktothecaller.

21

Callee

Parameters Returnvalue

Caller

Java Constructs - Methods

Page 22: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

public void run() {println(“Hypotenuse of 3 and 4 is: “);println(hypotenuse(3, 4));

}

private double hypotenuse(double a, double b) {return Math.sqrt(a*a + b*b);

}

22

Java Constructs - Methods

Page 23: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Approachingprogramtraces• Localvariablesinthecalleraredistinctfromlocalvariablesinthecallee• Parametersarejustassignednamesbytheorderinwhichthey’repassed•Writevaluesabovevariablenamesasyougothroughtheprogram(ordrawstackcardboxes)

23

Java Constructs - Methods

Page 24: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

24

Program Trace

Page 25: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

25

Program Tracepublic void run() {

String str = “Yay!! It is Valentine’s Day.”;println(getValentine(str, 6));...

}

private String getValentine(String str, int num1) {

num1 *= 2;

return str.substring(num1, str.length() – 1);

}

run

str Yay!!ItisValentine’sDay.

Page 26: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

26

Program Tracepublic void run() {

String str = “Yay!! It is Valentine’s Day.”;println(getValentine(str, 6));...

}

private String getValentine(String str, int num1) {

num1 *= 2;

return str.substring(num1, str.length() – 1);

}

run

str Yay!!ItisValentine’sDay.

Page 27: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

27

Program Tracepublic void run() {

String str = “Yay!! It is Valentine’s Day.”;println(getValentine(str, 6));...

}

private String getValentine(String str, int num1) {

num1 *= 2;

return str.substring(num1, str.length() – 1);

}

run

str Yay!!ItisValentine’sDay.

Page 28: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

28

Program Tracepublic void run() {

String str = “Yay!! It is Valentine’s Day.”;println(getValentine(str, 6));...

}

private String getValentine(String str, int num1) {

num1 *= 2;

return str.substring(num1, str.length() – 1);

}

run

str

getValentine

str

num1

Yay!!ItisValentine’sDay.

6

Yay!!ItisValentine’sDay.

Page 29: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

29

Program Tracepublic void run() {

String str = “Yay!! It is Valentine’s Day.”;println(getValentine(str, 6));...

}

private String getValentine(String str, int num1) {

num1 *= 2;

return str.substring(num1, str.length() – 1);

}

run

str

getValentine

str

num1

Yay!!ItisValentine’sDay.

12

Yay!!ItisValentine’sDay.

Page 30: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

30

Program Tracepublic void run() {

String str = “Yay!! It is Valentine’s Day.”;println(getValentine(str, 6));...

}

private String getValentine(String str, int num1) {

num1 *= 2;

return str.substring(num1, str.length() – 1);

}

run

str

getValentine

str

num1

Yay!!ItisValentine’sDay.

12

Yay!!ItisValentine’sDay.

27

Page 31: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

31

Program Tracepublic void run() {

String str = “Yay!! It is Valentine’s Day.”;println(getValentine(str, 6));...

}

private String getValentine(String str, int num1) {

num1 *= 2;

return str.substring(num1, str.length() – 1);

}

run

str

getValentine

str

num1

Yay!!ItisValentine’sDay.

12

Yay!!ItisValentine’sDay.

“Valentine’sDay”

Page 32: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Program Tracepublic void run() {

String str = “Yay!! It is Valentine’s Day.”;println(getValentine(str, 6));...

}

run

str Yay!!ItisValentine’sDay.

Valentine’sDay(Console)

Page 33: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

33

Program Tracerun

candy

public void run() {

...

int candy = 5;

int love= 6;

candy = howMuchCandy(candy, love);

println(“I got “ + candy + “ candy(ies)”);

}

private int howMuchCandy(int candy, int love) {

int num3 = love + candy / 2;

return num3 % 3;

}

5

Page 34: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

34

Program Tracepublic void run() {

...

int candy = 5;

int love = 6;

candy = howMuchCandy(candy, love);

println(“I got “ + candy + “ candy(ies)”);

}

private int howMuchCandy(int candy, int love) {

int num3 = love + candy / 2;

return num3 % 3;

}

runcandy

love

5

6

Page 35: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

35

Program Tracepublic void run() {

...

int candy = 5;

int love = 6;

candy = howMuchCandy(candy, love);

println(“I got “ + candy + “ candy(ies)”);

}

private int howMuchCandy(int candy, int love) {

int num3 = love + candy / 2;

return num3 % 3;

}

runcandy

love

5

6

Page 36: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

36

Program Tracepublic void run() {

...

int candy = 5;

int love = 6;

candy = howMuchCandy(candy, love);

println(“I got “ + candy + “ candy(ies)”);

}

private int howMuchCandy(int candy, int love) {

int num3 = love + candy / 2;

return num3 % 3;

}

runcandy

love

5

6

Page 37: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

37

Program Tracepublic void run() {

...

int candy = 5;

int love = 6;

candy = howMuchCandy(candy, love);

println(“I got “ + candy + “ candy(ies)”);

}

private int howMuchCandy(int candy, int love) {

int num3 = love + candy / 2;

return num3 % 3;

}

runcandy

love

5

6

howMuchCandy

candy

love

5

6

Page 38: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

38

Program Tracepublic void run() {

...

int candy = 5;

int love = 6;

candy = howMuchCandy(candy, love);

println(“I got “ + candy + “ candy(ies)”);

}

private int howMuchCandy(int candy, int love) {

int num3 = love + candy / 2;

return num3 % 3;

}

runcandy

love

5

6

howMuchCandy

candy

love

num3

5

6

8

Page 39: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

39

Program Tracepublic void run() {

...

int candy = 5;

int love = 6;

candy = howMuchCandy(candy, love);

println(“I got “ + candy + “ candy(ies)”);

}

private int howMuchCandy(int candy, int love) {

int num3 = love + candy / 2;

return num3 % 3; // 8 % 3 = 2

}

runcandy

love

5

6

howMuchCandy

candy

love

num3

5

6

8

Page 40: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

40

Program Tracepublic void run() {

...

int candy = 5;

int love = 6;

candy = howMuchCandy(candy, love);

println(“I got “ + candy + “ candy(ies)”);

}

runcandy

love

2

6

Page 41: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

41

Program Tracepublic void run() {

...

int candy = 5;

int love = 6;

candy = howMuchCandy(candy, love);

println(“I got “ + candy + “ candy(ies)”);

}

runcandy

love

2

6

Valentine’sDayIgot2candy(ies)(Console)

Page 42: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

• Trickyspots: precedence,parameter/variablenames…•Drawpictures!/Labelvariablevalues

42

Program Trace

Page 43: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Graphics + Animation

43

Page 44: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

• LookatlectureslidesforlistsofdifferentGObjecttypesandtheirmethods•Remember:thexandyofGRect,GOval,etc.istheirupperleftcorner,butthexandyofGLabel isitsleftmostbaselinecoordinate.•Remember:alabel’sheightisgottenfromgetAscent().

44

Graphics

Page 45: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

45

while (CONDITION) {updateGraphics(); // e.g. move GObjectperformChecks(); // e.g. check game conditionspause(PAUSE_TIME);

}

Standardformatforanimationcode:

Animation

Page 46: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Memory

46

Page 47: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

• Stackandheap• Stack iswherelocalvariableslive• Heap iswhereobjectslive

•Whenyoumakeanobject,thelocalvariable(whatyounamedit)isaboxthatstoresanaddressontheheap wheretheobjectactuallylives.•Whenyoumakeaprimitive,thelocalvariableisaboxthatstorestheactualvalue.

47

Memory

Page 48: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

• ==isdangerousbecauseitcompareswhat’sinthevariableboxes!• Forprimitives,ok• Forobjects,comparestheiraddresses!Soonlytrueifthey’retheexactsameobjectlivingintheexactsameplace.

48

Memory

Page 49: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Parameters: whenyoupassaparameter,Javapassesacopyofwhateverisinthevariable’sbox.• Forprimitives– acopyoftheirvalue• Forobjects– acopyoftheiraddress! Sothere’sstillonly1objectversion

49

Memory

Page 50: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

public void run() {GRect rect = new Grect(0,0,50,50);fillBlue(rect);add(rect); // rect is blue!

}

private void fillBlue(GRect rect) {rect.setFilled(true);rect.setColor(Color.BLUE);

}

50

Memory

Page 51: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

public void run() {int x = 2;addTwo(x);println(x); // x is still 2!

}

private void addTwo(int x) {x += 2; // this modifies addTwo’s COPY!

}

51

Memory

Page 52: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

public void run() {int x = 2;x = addTwo(x);println(x); // x is 4!

}private int addTwo(int x) {

x += 2; // this modifies addTwo’s COPY!return x;

}

52

Memory – Getting Changes to Copies

Page 53: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Event-driven Programming

53

Page 54: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•MouseEvents!• Two waysforJavatoexecuteyourcode:fromrun()andfromeventhandler(mouseClicked,mouseMoved,etc.).• Theseprogramsareasynchronous – codeisnotruninorderanymore,sinceyoudon’tknowwhentheuserwillinteractwithyourprogram!

54

Event-Driven Programming

Page 55: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

1. Signupfornotificationsforkeyormouseevents2. Implementthemethodcorrespondingtowhat

eventyoucareabout(e.g.mousePressed,mouseMoved).

3. Javawillcallthatmethodwheneverthecorrespondingeventoccurs.

55

Event-Driven Programming

Page 56: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Let’swriteaprogramlike“mysterysquare”,butwhenyouclicktheshapechangesbetweenasquareandacircle.

Theshapesshouldalwaysbethesamerandomcolor,evenifyouclickinbetweencolorschanging.

56

Event-Driven Programming

Page 57: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

57

Refresher: Mystery Square

Page 58: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Modifications:•Haveasquareandcircle atthesametime•Changethecolorsofboth everyPAUSE_TIME•Onclick,addoneandremovetheother

58

Color-Changing Shape

Page 59: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

private static final int SQUARE_SIZE = 100;private static final int PAUSE_TIME = 100;private GRect square;private GOval circle;private boolean isShowingSquare = true;

private RandomGenerator rgen = RandomGenerator.getInstance();

59

Constants + Instance Variables

Page 60: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

public void run() {setup();while (true) {

Color c = rgen.nextColor();square.setColor(c);circle.setColor(c);pause(PAUSE_TIME);

}}

60

Color-Changing Shape

Page 61: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

private void setup() {double x = (getWidth() – SQUARE_SIZE) / 2.0;double y = (getHeight() – SQUARE_SIZE) / 2.0;square = new GRect(x, y, SQUARE_SIZE, SQUARE_SIZE);circle = new GOval(x, y, SQUARE_SIZE, SQUARE_SIZE);square.setFilled(true);circle.setFilled(true);add(square); // only add square!addMouseListeners();

}61

Color-Changing Shape

Page 62: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

public void mouseClicked(MouseEvent e) {if (isShowingSquare) {

remove(square);

add(circle);

} else {

remove(circle);

add(square);

}

isShowingSquare = !isShowingSquare;

}62

Color-Changing Shape

Page 63: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Characters and Strings

63

Page 64: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Achar isaprimitivetype thatrepresentsasingleletter,digit,orsymbol.Usessinglequotes(‘’).•Computersrepresentchars asnumbersunderthehood(ASCIIencodingscheme).•Astringisanimmutableobject thatrepresentsasequenceofcharacters.Usesdoublequotes(“”).

64

Characters and Strings

Page 65: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

char uppercaseA = ‘A’;char uppercaseB = (char)(uppercaseA + 1);int lettersInAlphabet = ‘Z’ – ‘A’ + 1;// equivalent: ‘z’ – ‘a’ + 1// A to Z and a to z are sequential numbers.

65

Characters

Page 66: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

66

Characters

Page 67: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Note: charsareprimitives.Thismeanswecan’tcallmethodsonthem!• InsteadweusetheCharacter classandcallmethodsonit.Wepassinthecharacterofinterestasaparameter.• Thesemethodsdonotchangethechar!Theyreturnamodifiedchar.

67

Characters

Page 68: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

char ch = ‘a’;Character.toUpperCase(ch); // does nothing!ch.toUpperCase(); // won’t compile!ch = Character.toUpperCase(ch); // ✔

if (Character.isUpperCase(ch)) {println(ch + “ is upper case!”);

}

68

Characters

Page 69: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

•Note: stringsare(immutable)objects.Thismeanswecan callmethodsonthem!•Wecannotchangeastringaftercreatingit.• Stringscanbecombinedwithints,doubles,chars,etc.

69

Strings

Page 70: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

70

Strings

Page 71: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

String str = “Hello world!”; // no “new” neededstr.toUpperCase(); // does nothing!str = str.toUpperCase(); // ✔

for (int i = 0; i < str.length(); i++) {println(str.charAt(i));

}// prints each char on its own line

71

Strings

Page 72: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

String str = ”’ello mate!”;str = str.substring(1);str = ‘H’ + str; // str = “Hello mate!”String newStr = “”;for (int i = 0; i < str.length(); i++) {

newStr = str.charAt(i) + newStr;}// newStr = “!etam olleH”

72

Putting it ALL together

Page 73: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

println(“B” + 8 + 4);// prints “B84”println(“B” + (8 + 4));// prints “B12”println(’A’ + 5 + “ella”);// prints “70ella (note: ‘A’ corresponds to 65)”println((char)(‘A’ + 5) + “ella”);// prints “Fella”

73

Type Conversion Mayhem

Page 74: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

• Thisseemsnonsensical- butit’snot!(kindof)• Justuseprecedencerules andkeeptrackofthetypealongtheway.

74

println(‘A’ + 5 + “ella”);// ‘A’ + 5 is int (70), int + “ella” is stringprintln((char)(‘A’ + 5) + “ella”);// ‘A’ + 5 is char (‘F’), char + “ella” is string

Type Conversion Mayhem

Page 75: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Letswriteamethodthat,givenastring,removesallstringswithinasterisksandreturnstheresult.

75

String str = “int s = 2; * This is 2 *”;println(removeComments(str)); // “int s = 2; ”str = “Hi * Hello * Hello”;println(removeComments(str)); // “Hi Hello“str = “No comments!”;println(removeComments(str)); // “No comments!“

Strings Practice

Page 76: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

• SuperhelpfulStringspattern:givenastring,iteratethroughandbuildupanewstring.(Sincestringsareimmutable!)

76

String oldStr = ...String newStr = “”;for (int i = 0; i < oldStr.length(); i++) {

// build up newStr}

Strings Practice

Page 77: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

private String removeComments(String str) {String newStr = “”;boolean inComment = false;for (int i = 0; i < str.length(); i++) {

if (str.charAt(i) == ‘*’) inComment = !inComment;

// Note: if at end of comment, inComment already false!if (!inComment && str.charAt(i) != ‘*’) {

newStr += str.charAt(i);}

}return newStr; // DON’T FORGET!!

}

77

Strings Practice

Page 78: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

Parting Words

78

Page 79: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

• Trytogettoeveryproblem•Don’trushtocodingtooquickly•Pseudocode!• Lookoverthepracticemidterm

79

Parting Words

Page 80: CS106A Review Session - Stanford University...Event-Driven Programming Let’s write a program like “mystery square”, but when you click the shape changes between a square and

80