cs106a review session - stanford university...event-driven programming let’s write a program like...
TRANSCRIPT
CS106A Review Session
Saturday Feb. 11, 2017Maria Yang
1
Topic List•Karel• Javaconstructs•Graphics+Animation•Memory (Pass-by-referencevs.passbyvalue)• Event-drivenprogramming•CharactersandStrings
2
Karel
3
Karel• Tips:• Pseudocodefirst• Decomposetheproblem•Mightbelimitationsonconstructs• E.g.noJavafeatures(variables,break,etc.)
4
Trick-or-Treat Karel
5
Karel Needs Love
Karelisinaworldwithwalkwaystohousesthathavevalentines.Karelshouldgotoeveryhouseinorder,goupthewalkwayandtakeallthevalentines(beepers).Housewalkwayscanbeanydistanceapart,andhaveguidewallsontheleftandrightuptothevalentine.
6
Karel Needs Love
7
Demo: Karel Needs Love
Loop:- Gotonexthouse- GetValentines
8
Gotonexthouse:- movealongleftwall
GetValentines:- traversewalkway- takevalentine- traversewalkway
Karel Needs Love
public void run() {while (frontIsClear()) {
goToNextHouse();getValentines();if (frontIsClear()) {
move();}
}}
9
Karel Needs Love
private void goToNextHouse() {while (leftIsBlocked()) {
move();}
}
10
Karel Needs Love
private void getValentines() {turnLeft();traverseWalkway();takeValentine();turnAround();traverseWalkway();turnLeft();
}
11
Karel Needs Love
private void traverseWalkway() {move();while (leftIsBlocked() && rightIsBlocked()) {
move();}
}
12
Karel Needs Love
private void takeValentine() {while (beepersPresent()) {
pickBeeper();}
}
13
Karel Needs Love
Java Constructs
14
•Variabletypes:primitives(int,double,…)+objects(GRect,Goval,…)•Controlstatements:if,while,for,switch•Whatiseachusefulfor?
•Methods
15
Java Constructs
•Variabletypes:primitives(int,double,…)+objects(GRect,Goval,…)•Controlstatements:if,while,for,switch•Whatiseachusefulfor?
•Methods
16
Java Constructs
•ReadinuserinputuntilyouhittheSENTINEL• Iteratethroughastring•MoveKareltoawall
17
WHILEFORWHILE
For or While?
•Variabletypes:primitives(int,double,…)+objects(GRect,Goval,…)•Controlstatements:if,while,for,switch•Whatiseachusefulfor?
•Methods
18
Java Constructs
•Amethodisaroutineofinstructionsthatmaytakesomeinputandgivebacksomeoutput.
19
MethodParameters Returnvalue
Java Constructs - Methods
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
•Parameters arehowthecaller givesinformationtothecallee.Areturnvalueishowthecallee givesinformationbacktothecaller.
21
Callee
Parameters Returnvalue
Caller
Java Constructs - Methods
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
•Approachingprogramtraces• Localvariablesinthecalleraredistinctfromlocalvariablesinthecallee• Parametersarejustassignednamesbytheorderinwhichthey’repassed•Writevaluesabovevariablenamesasyougothroughtheprogram(ordrawstackcardboxes)
23
Java Constructs - Methods
24
Program Trace
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.
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.
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.
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.
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.
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
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”
Program Tracepublic void run() {
String str = “Yay!! It is Valentine’s Day.”;println(getValentine(str, 6));...
}
run
str Yay!!ItisValentine’sDay.
Valentine’sDay(Console)
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
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
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
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
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
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
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
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
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)
• Trickyspots: precedence,parameter/variablenames…•Drawpictures!/Labelvariablevalues
42
Program Trace
Graphics + Animation
43
• LookatlectureslidesforlistsofdifferentGObjecttypesandtheirmethods•Remember:thexandyofGRect,GOval,etc.istheirupperleftcorner,butthexandyofGLabel isitsleftmostbaselinecoordinate.•Remember:alabel’sheightisgottenfromgetAscent().
44
Graphics
45
while (CONDITION) {updateGraphics(); // e.g. move GObjectperformChecks(); // e.g. check game conditionspause(PAUSE_TIME);
}
Standardformatforanimationcode:
Animation
Memory
46
• Stackandheap• Stack iswherelocalvariableslive• Heap iswhereobjectslive
•Whenyoumakeanobject,thelocalvariable(whatyounamedit)isaboxthatstoresanaddressontheheap wheretheobjectactuallylives.•Whenyoumakeaprimitive,thelocalvariableisaboxthatstorestheactualvalue.
47
Memory
• ==isdangerousbecauseitcompareswhat’sinthevariableboxes!• Forprimitives,ok• Forobjects,comparestheiraddresses!Soonlytrueifthey’retheexactsameobjectlivingintheexactsameplace.
48
Memory
•Parameters: whenyoupassaparameter,Javapassesacopyofwhateverisinthevariable’sbox.• Forprimitives– acopyoftheirvalue• Forobjects– acopyoftheiraddress! Sothere’sstillonly1objectversion
49
Memory
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
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
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
Event-driven Programming
53
•MouseEvents!• Two waysforJavatoexecuteyourcode:fromrun()andfromeventhandler(mouseClicked,mouseMoved,etc.).• Theseprogramsareasynchronous – codeisnotruninorderanymore,sinceyoudon’tknowwhentheuserwillinteractwithyourprogram!
54
Event-Driven Programming
1. Signupfornotificationsforkeyormouseevents2. Implementthemethodcorrespondingtowhat
eventyoucareabout(e.g.mousePressed,mouseMoved).
3. Javawillcallthatmethodwheneverthecorrespondingeventoccurs.
55
Event-Driven Programming
Let’swriteaprogramlike“mysterysquare”,butwhenyouclicktheshapechangesbetweenasquareandacircle.
Theshapesshouldalwaysbethesamerandomcolor,evenifyouclickinbetweencolorschanging.
56
Event-Driven Programming
57
Refresher: Mystery Square
Modifications:•Haveasquareandcircle atthesametime•Changethecolorsofboth everyPAUSE_TIME•Onclick,addoneandremovetheother
58
Color-Changing Shape
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
public void run() {setup();while (true) {
Color c = rgen.nextColor();square.setColor(c);circle.setColor(c);pause(PAUSE_TIME);
}}
60
Color-Changing Shape
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
public void mouseClicked(MouseEvent e) {if (isShowingSquare) {
remove(square);
add(circle);
} else {
remove(circle);
add(square);
}
isShowingSquare = !isShowingSquare;
}62
Color-Changing Shape
Characters and Strings
63
•Achar isaprimitivetype thatrepresentsasingleletter,digit,orsymbol.Usessinglequotes(‘’).•Computersrepresentchars asnumbersunderthehood(ASCIIencodingscheme).•Astringisanimmutableobject thatrepresentsasequenceofcharacters.Usesdoublequotes(“”).
64
Characters and Strings
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
66
Characters
•Note: charsareprimitives.Thismeanswecan’tcallmethodsonthem!• InsteadweusetheCharacter classandcallmethodsonit.Wepassinthecharacterofinterestasaparameter.• Thesemethodsdonotchangethechar!Theyreturnamodifiedchar.
67
Characters
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
•Note: stringsare(immutable)objects.Thismeanswecan callmethodsonthem!•Wecannotchangeastringaftercreatingit.• Stringscanbecombinedwithints,doubles,chars,etc.
69
Strings
70
Strings
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
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
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
• 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
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
• SuperhelpfulStringspattern:givenastring,iteratethroughandbuildupanewstring.(Sincestringsareimmutable!)
76
String oldStr = ...String newStr = “”;for (int i = 0; i < oldStr.length(); i++) {
// build up newStr}
Strings Practice
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
Parting Words
78
• Trytogettoeveryproblem•Don’trushtocodingtooquickly•Pseudocode!• Lookoverthepracticemidterm
79
Parting Words
80