CS 106A, Lecture 27 Final Exam Review 1 - Stanford University · 2017-08-15 · •1D Arrays •2D...

Post on 03-Jul-2018

218 views 0 download

transcript

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

CS106A,Lecture27FinalExamReview1

2

Plan for today•Announcements/Examlogistics•Graphics,Animation,Events•1DArrays•2DArrays•ArrayList

3

Plan for today•Announcements/Examlogistics•Graphics,Animation,Events•1DArrays•2DArrays•ArrayList

4

Final exam• Isthe finalexam cumulative?• What will betested on the finalexam?• What about allthis stuff you aren’t covering today?

– ExpressionsandVariables– JavaControlStatements– ConsolePrograms– Methods,parameters,returns– Randomness– Strings andchars– Scanners andfileprocessing– Memory

• Isthe finalexam going tobedifficult/curved?• Howcan Ipractice forthe final?

Midterm review sessionwas the recorded sectionon Fridayof Week 4

5

Practicing for the final• Reviewconceptsyou’reunsureof• Reviewconceptsfrompreviousassignments• Dosectionproblems• Dopracticefinalunderrealconditions• codestepbystep.com

6

Plan for today•Announcements/Examlogistics•Graphics,Animation,Events•1DArrays•2DArrays•ArrayList

7

Graphics• LookatlectureslidesforlistsofdifferentGObject typesandtheirmethods

• Remember:thexandyofGRect,GOval,etc.Istheirupperleftcorner,butthexandyofGLabel isitsleftmostbaselinecoordinate.

• Rememberforlabels:getHeight()=getAscent()+getDescent().

8

AnimationStandardformatforanimationcode:

while (condition) {update graphicsperform checkspause(PAUSE_TIME);

}

9

Events• TwowaysforJavatorunyourcode:fromrun()andfromeventhandlers(mouseClicked,mouseMoved,actionPerformed,etc.)

• Eventhandlersmusthaveexactlythespecifiedsignatureotherwisetheywon’twork!

e.g.public void mouseClicked(MouseEvent e)

• Ifyouneedtomodifysomethinginaneventhandlerthatyouuseelsewhereinyourcode,itshouldbeaninstancevariable(e.g.paddleinBreakout!)

10

Demo: Seeker

11

Seeker• Redsquareisthetarget• Transparentsquareistheseeker• Theseekershouldmovetowardsandengulfthetarget• Canchangetargetlocationbyclickingonthescreen

12

Instance variables

13

run()public void run() {

initTarget();initSeeker();

// Always keep seeking the targetwhile (true) {

seek();pause(PAUSE_TIME);

}}

14

run()public void run() {

initTarget();initSeeker();

// Always keep seeking the targetwhile (true) {

seek();pause(PAUSE_TIME);

}}

15

initTarget()

16

initSeeker()

17

run()public void run() {

initTarget();initSeeker();

// Always keep seeking the targetwhile (true) {

seek();pause(PAUSE_TIME);

}}

18

seek()

19

moveAmount()

20

mouseClicked()

21

Plan for today•Announcements/Examlogistics•Graphics,Animation,Events•1DArrays•2DArrays•ArrayList

22

1D Arrays• Anarray isafixed-lengthlistofasingletypeofthing.• Anarraycanstoreprimitives andobjects.• Youcannotcallmethodsonarraysi.e.nomyArray.contains().• GetthelengthbysayingmyArray.length.(Noparentheses!)• PrintarraywithArrays.toString(myArray),not println(myArray)!

[2, 4, 6, 8] [I@4ddced80

23

Program traces• Localvariablesareseparate acrossmethods• Parametersarejustassignednamesbytheorderinwhichthey’repassed

• Drawchangestovariablesasyougothroughtheprogram• Objectsvsprimitivebehaviorforparameters

A.Prints [5,10,15]5B.Prints [5,10,15]7C.Prints [5,20,15]5D.Prints [5,20,15]7

24

Trace

25

Trace

Output:[4, 0, 2] 4 1[4, 0, 2] 3[8, 0, 4] 1 1[8, 0, 4] 6

26

Extra 1D Array problemWritethe method int longestSortedSequence(int[] array)

e.g.int[] array = {3, 8, 10, 1, 9, 14, -3, 0, 14, 207, 56, 98, 12}

Sorted inthis casemeans nondecreasing,soasequence could contain duplicates:

e.g.int[] array = {17, 42, 3, 5, 5, 5, 8, 2, 4, 6, 1, 19}

Link:http://www.codestepbystep.com/problem/view/java/arrays/longestSortedSequence

3 3 4 2 1

2 3 25

27

Plan for today•Announcements/Examlogistics•Graphics,Animation,Events•1DArrays•2DArrays•ArrayList

28

2D Arrays = Arrays of Arrays!int[][] a = new int[3][4];

a[0][0] a[0][1] a[0][2] a[0][3]

a[1][0] a[1][1] a[1][2] a[1][3]

a[2][0] a[2][1] a[2][2] a[2][3]

Outerarray

29

Chess• Knight:moves inan”L”-shape (two steps inone direction,one stepinaperpendicular direction)

30

knightCanMove()boolean knightCanMove(String[][] board,

int startRow, int startCol,int endRow, int endCol)

• (startRow,startCol)mustcontainaknight• (endRow,endCol)mustbeempty• (endRow,endCol)mustbereachablefrom(startRow,startCol)inasinglemove

• Assumethat(startRow,startCol)and(endRow,endCol)arewithinboundsofarray

31

knightCanMove()

0 1 2 3 4 5 6 7

0 ”king”

1 ”knight”

2

3 ”rook”

4

5

6

7

32

0 1 2 3 4 5 6 7

0 ”king”

1 ”knight”

2

3 ”rook”

4

5

6

7

knightCanMove()

0 1 2 3 4 5 6 7

0 ”king”

1 ”knight”

2

3 ”rook”

4

5

6

7

knightCanMove(board, 2, 2, 3, 4)

Noknight at(2,2)

returns false

33

0 1 2 3 4 5 6 7

0 ”king”

1 ”knight”

2

3 ”rook”

4

5

6

7

knightCanMove()

0 1 2 3 4 5 6 7

0 ”king”

1 ”knight”

2

3 ”rook”

4

5

6

7

knightCanMove(board, 1, 2, 0, 4)

Spaceoccupied

returns false

34

knightCanMove()

0 1 2 3 4 5 6 7

0 ”king”

1 ”knight”

2

3 ”rook”

4

5

6

7

knightCanMove(board, 1, 2, 3, 2)

(1,2)to(3,2)isnotavalidmove

returns false

35

knightCanMove()

0 1 2 3 4 5 6 7

0 ”king”

1 ”knight”

2

3 ”rook”

4

5

6

7

knightCanMove(board, 1, 2, 3, 3)

Knightisat(1,2)and(3,3)isemptyand(1,2)->(3,3)isavalidmove

returns true

36

knightCanMove()// This method returns true if the starting square contains a knight,// the end square is empty, and the knight can legally move from the// start square to the end square.private boolean knightCanMove(String[][] board, int startRow,

int startCol, int endRow, int endCol) {

}

37

knightCanMove()// This method returns true if the starting square contains a knight,// the end square is empty, and the knight can legally move from the// start square to the end square.private boolean knightCanMove(String[][] board, int startRow,

int startCol, int endRow, int endCol) {if (board[startRow][startCol].equals("knight")) {

}

}

38

knightCanMove()// This method returns true if the starting square contains a knight,// the end square is empty, and the knight can legally move from the// start square to the end square.private boolean knightCanMove(String[][] board, int startRow,

int startCol, int endRow, int endCol) {if (board[startRow][startCol].equals("knight")) {

if (board[endRow][endCol].equals("")) {

}}

}

39

knightCanMove()// This method returns true if the starting square contains a knight,// the end square is empty, and the knight can legally move from the// start square to the end square.private boolean knightCanMove(String[][] board, int startRow,

int startCol, int endRow, int endCol) {if (board[startRow][startCol].equals("knight")) {

if (board[endRow][endCol].equals("")) {int rowDifference = Math.abs(startRow - endRow);int colDifference = Math.abs(startCol - endCol);if ((rowDifference == 1 && colDifference == 2) ||

(rowDifference == 2 && colDifference == 1)) {return true;

}}

}

}

40

knightCanMove()// This method returns true if the starting square contains a knight,// the end square is empty, and the knight can legally move from the// start square to the end square.private boolean knightCanMove(String[][] board, int startRow,

int startCol, int endRow, int endCol) {if (board[startRow][startCol].equals("knight")) {

if (board[endRow][endCol].equals("")) {int rowDifference = Math.abs(startRow - endRow);int colDifference = Math.abs(startCol - endCol);if ((rowDifference == 1 && colDifference == 2) ||

(rowDifference == 2 && colDifference == 1)) {return true;

}}

}return false;

}

41

Plan for today•Announcements/Examlogistics•Graphics,Animation,Events•1DArrays•2DArrays•ArrayList

42

ArrayList• AnArrayList isaflexible-lengthlistofasingletypeofthing.• AnArrayList canonlystoreobjects.

– Forprimitivesusee.g.ArrayList<Integer> insteadofArrayList<int>.(Integer isawrapperclassforint)

– Otherwrapperclasses:Double insteadofdouble,Character insteadofchar,Boolean insteadofboolean.

• AnArrayList hasavarietyofmethodsyoucanuselike.contains,.get,.add,.remove,.size,etc.

43

Array vs ArrayList• Array

– Fixedsize– Efficient(notaconcerninthisclass)– Nomethods,canonlyusemyArray.length (noparentheses!)– Canstoreanyobjectorprimitive

• ArrayList– Expandable– LessefficientthanArray(notaconcerninthisclass)– Convenientmethodslike.add(),.remove(),.contains()– Cannotstoreprimitives,sousetheirwrapperclassesinstead

44

deleteDuplicates()private void deleteDuplicates(ArrayList<String> list)

• Guaranteedthatlistisinsortedorder• {"be","be","is","not","or","question","that","the","to","to"}becomes{“be”,“is”,“not”,“or”,“question”,“that”,“the”,“to”}

• Solutionstrategy:– LoopthroughArrayList– Comparepairsofelements– Ifelement.equals(nextElement),removeelementfromthelist

45

deleteDuplicates• LoopthroughArrayList• Comparepairsofelements• Ifelement.equals(nextElement),removeelementfromthelist

46

deleteDuplicatesReverse• LoopthroughArrayList inreverse• Comparepairsofelements• Ifelement.equals(previousElement),removeelementfromthelist

47

Recap•Announcements/Examlogistics•Graphics,Animation,Events•1DArrays•2DArrays•ArrayList

Nexttime:FinalExamReview2