1 / 55

Review for the AP CS Exam

Review for the AP CS Exam. Object Oriented Program Design Program Design Read and Understand class specifications and relationships among the classes (has a and is a relationships) A/B:Decompose a problem into classes, define relationships and responsibilities of those classes. Program design.

indra
Download Presentation

Review for the AP CS Exam

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Review for the AP CS Exam • Object Oriented Program Design • Program Design • Read and Understand class specifications and relationships among the classes(has a and is a relationships) • A/B:Decompose a problem into classes, define relationships and responsibilities of those classes

  2. Program design • Top down approach • Make a list of all of the things that a program must accomplish • Each of those things becomes its own module (perhaps a method or perhaps a class with several methods) • Bottom up approach • Starts with specific, detailed way of achieving something(ie recursive area fill or interacting with a piece of hardware) • Builds program up around that detail

  3. Class design • Class Design • Design and implement a class • Design an interface (remember that an interface has only methods, no data) • Extend a class using inheritance (Design question) • Remember that any class that implements an interface_____________________________ • Use extends and implements appropriately • declare constructors and methods with • meaningful names • appropriate parameters • appropriate return types (remember constructors _______________________________________)

  4. Class design • Class Design • appropriate declaration of methods as private or public • all data should be ______________

  5. Program Implementation • Program Implementation • Classes that fill common needs should be built so they can be reused by other programs. OO design is an important part of program implementation • Implementation Techniques • Encapsulation and information hiding • Procedural abstraction

  6. Program Implementation • Programming constructs • Primitives vs references • Remember that references must be associated with an object • Beware of aliasing:______________________________________________________________________________

  7. Floating Point Number Probs Here is an explanation from borland’s web site; • Round-Off Problems : • One of the problems with floating point numbers is round-off. Round off errors occur when attempting to represent certain numbers in any number base. For example, 1/3 is not exactly representable in base ten, while 1/10th is easily representable. But since we're dealing with computers, we are specifically in base two numbers. As opposed to base ten, 1/10th is not exactly representable in base two. For example, the fractional portions of base two are: 1/2 1/4 1/8 1/16 1/32 1/64 1/128 1/256 1/512 The numbers 1/2, 1/4, 1/8, all powers of two, are exactly representable in a computer. But since 1/10 lies between 1/8 and 1/16, it is not exactly representable using binary notation. So internally the computer has to decide which fractional binary portions to add together to sum close to 1/10. For example: 1/2 1/4 1/8 1/16 1/32 1/64 1/128 1/256 1/512 0 0 0 1 1 1 0 0 0 this adds up to: 0.1093 which is close to 0.1000 but could easily be rounded to .11 so the computer internal algorithm must try to find another combination of binary fractions which come closer to 0.1000 When it's internal algorithm is satisfied, it will have a number which is CLOSE to 1/10th but not EXACT. This inexactness is known as ROUND-OFF error.

  8. Constant Declarations • Constant declarations • final double WIDTH = 1.1619; • Use these whenever you are using a numeric value that you type several places in a program • Variable declarations • Scope of variables • Shadowing problem: Most local variable gets precedence

  9. Method declarations • Method declarations • A method’s signature consists of name, parameter types and order of parameters • Overloaded methods have the same______________________ but different___________________ • Constructors are often overloaded • What is a static method?_________________________________________________ • What is a private method?__________________________________

  10. Interface Declarations • Interfaces • A collection of methods that a class must implement • An interface you should know • interface java.lang.Comparable • int compareTo(Object other)// return value < 0 if this is less than other// return value = 0 if this is equal to other// return value > 0 if this is greater than other

  11. Interface Declarations Example Double x = new Double(1.618); Double y = new Double(3.14159); //Write a statement that compares x to y and prints out “phi is less than pi”

  12. Math Operators • Math ops • +,-,/,*,% • two types of division • type casting (int) and (double) • Students are expected to understand "truncation towards 0" behavior as well as the fact that positive floating-point numbers can be rounded to the nearest integer as (int)(x + 0.5), negative numbers as (int)(x - 0.5) • Math.abs(double x), Math.sqrt(double x), Math.pow(double base, double exp)

  13. Control • Control techniques • Methods • break; //breaks out of nearest ________ • conditional (if, if else, switch case optional) • iteration (for and while only required) • recursion • Powerful technique when a method invokes itself • Must have some sort of stopping or base case • Remember to use McCarthy method or something similar to trace • many method calls decrease efficiency

  14. Program Analysis • Program Analysis • Testing/Debugging • Test Libraries and Classes in isolation • Identify boundary cases • Understand error handling • ArithmeticException • Divide by zero • IndexOutOfBoundsException • ClassCastException • Attempt to cast to subclass of which it is not an instance • NullPointerException • Needed an object, got the shaft!!! • IllegalArgumentException

  15. Analysis of Algorithms • Algo Analysis • Big Oh Notation • Asymptotic growth limit • O(n) linear • O(n2) quadratic (two dim array, nested for) • O(logn) divide and conquer(assume base 2, this is comp sci man!!) • O(1) constant time • O(nlogn) better sorting algo’s including logn= find where this element belongs and n to move each element into position

  16. Analysis of Algorithms

  17. Data Structures • int : 32 bit signed integer • double: 64 bit signed floating point • boolean: true or false

  18. Classes and Class Hierarchies • Remember chess piece example • abstract base class with abstract method isValidMove() • Children must redefine this method • Example of dynamic binding or late binding • Calls to isValidMove are _____________

  19. Classes and Class Hierarchies • “Cast down the hierarchy” • Ok to cast from Object to Integer assuming class is an Integer • Ok to cast from piece to pawn if you know the piece is a pawn • Children inherit all methods and classes (but cannot play with ______________) • Also, static methods and vars are one per class

  20. One/Two dimensional arrays • Once created a certain size, fixed • use .length, the member var • Use [ ] to access elements starting at 0 …length-1 • 0 and <length works for boundaries • Use array[0].length for column dimensions • Use r and c for loop control vars for ease of reading • Must create individual objects if array of references

  21. ArrayList • int size() • boolean add(Object x) • Object get(int index) • Object set(int index, Object x)// replaces the element at index with x// returns the element formerly at the specified position • void add(int index, Object x)// inserts x at position index, sliding elements // at position index and higher to the right // (adds 1 to their indices) and adjusts size • Object remove(int index) // removes element from position index, sliding elements // at position index + 1 and higher to the left // (subtracts 1 from their indices) and adjusts size

  22. Linked Lists • Singly • Doubly • Circular • Inserting, must use a trailer to link the previous node to new node (remember to use new command to create) and link this node to next • When removing, just point the previous node to this node’s next and the Java garbage collection will scoop up the idle node

  23. List Node public class ListNode { public ListNode(Object initValue, ListNode initNext) { value = initValue; next = initNext; } public Object getValue() { return value; } public ListNode getNext() { return next; } public void setValue(Object theNewValue) { value = theNewValue; } public void setNext(ListNode theNewNext) { next = theNewNext; } private Object value; private ListNode next; } Must typecast when pulling something out of the list, NOTE: Need have some way to compare if you intend to use a sorted list

  24. Stacks • ______________ data structures • Good when you need to untangle some type of operations that have to be suspended and returned to

  25. Stack interface public interface Stack { // postcondition: returns true if stack is empty, false otherwise boolean isEmpty(); // precondition: stack is [e1, e2, ..., en] with n >= 0 // postcondition: stack is [e1, e2, ..., en, x] void push(Object x); // precondition: stack is [e1, e2, ..., en] with n >= 1 // postcondition: stack is [e1, e2, ..., e(n-1)]; returns en // throws an unchecked exception if the stack is empty Object pop(); // precondition: stack is [e1, e2, ..., en] with n >= 1 // postcondition: returns en // throws an unchecked exception if the stack is empty Object peekTop(); }

  26. Queues • ______________ data structures • Good when you need to simulate some sort of time dependent operation • Good for holding items to be processed over time

  27. Queue Interface public interface Queue { // postcondition: returns true if queue is empty, false otherwise boolean isEmpty(); // precondition: queue is [e1, e2, ..., en] with n >= 0 // postcondition: queue is [e1, e2, ..., en, x] void enqueue(Object x); // precondition: queue is [e1, e2, ..., en] with n >= 1 // postcondition: queue is [e2, ..., en]; returns e1 // throws an unchecked exception if the queue is empty Object dequeue(); // precondition: queue is [e1, e2, ..., en] with n >= 1 // postcondition: returns e1 // throws an unchecked exception if the queue is empty Object peekFront(); } REMEMBER To ________________________all objects you pull out as needed

  28. Binary Trees • Ordered ones are called _____________ • Heaps have _______________________________ • Powerful divide and conquer structure

  29. Binary Trees • Traversals F C R M Pre: In: Post:

  30. Priority Queues • Queue that allows high priority items to move to the top (the minimal element) public interface PriorityQueue { // postcondition: returns true if the number of elements in // the priority queue is 0; otherwise, returns false boolean isEmpty(); // postcondition: x has been added to the priority queue; // number of elements in the priority queue is increased by 1 void add(Object x); // postcondition: The smallest item in the priority queue is removed // and returned; the number of elements in the priority queue // is decreased by 1 // throws an unchecked exception if the priority queue is empty Object removeMin(); // postcondition: The smallest item in the priority queue is returned; the // priority queue is unchanged // throws an unchecked exception if the priority queue is empty Object peekMin(); }

  31. To Be Continued… More tomorrow

  32. Analysis of Algorithms

  33. Sets • A set is a collection of unique objects • Does not allow ________________________ interface java.util.Set boolean add(Object x) adds element, returns true if successful boolean contains(Object x) returns true if x occurs in Set boolean remove(Object x) attempts to remove x, true if successful int size() returns number of elements in the Set Iterator iterator() returns an Iterator for the set

  34. Sets • TreeSet keys must implement________________ • A TreeSet gives you a balanced ______ • To get the values in order____________________________________________________________________ • HashSet needs a key that redefines ___________ and ______________ • If you add a pair that has an existing key,__________________________

  35. Maps • A map is an association of _________ and __________ interface java.util.Map Object put(Object key, Object value)// associates key with value// returns the value formerly associated with key// or null if key is not in the map Object get(Object key) Object remove(Object key) boolean containsKey(Object key) int size() Set keySet()

  36. HashMaps • HashMaps implement a hash table • (Use .75 full max as a guideline) • Uses your hashCode( ) method that is redefined as part of Object (but how do you know how big the table is?) • True or False: You are guaranteed to get the keys in order if you iterate over the keySet • The key used must be a distinct object, which is why I think HashMaps are stupid!!!

  37. TreeMaps • TreeMaps implement a balanced BST • All of the work of inserting and traversing is done for you • Your keys must implement ______________ • Once again, your keys must be a distinct object, which is pretty hokey • Attempting to insert a duplicate key will___________________________

  38. Iterators • Iterators allow traversal of a data set using a common iterface • java.util.Iterator • boolean hasNext() • Object next(); //will need to typecast this result • void remove(); //must be called after next • Think of an iterator as a flashing cursor between the letters of text

  39. ListIterators • ListIterators add _______________ and ______________ to the Iterator • __________________ • Get a ClassCastException if adding an element that is not like the others • Subsequent calls to next() unaffected by add • _____________________ • IllegalStateException if next() not called or if remove or add called since last call to next() • You can always reset a iterator to the front of the list be recreating it

  40. Strings • class java.lang.String implements java.lang.Comparable • int compareTo(Object other)// specified by java.lang.Comparable • boolean equals(Object other) • int length() • String substring(int from, int to) // returns the substring beginning at from // and ending at to-1 • String substring(int from)// returns substring(from, length()) • int indexOf(String s)// returns the index of the first occurrence of s; // returns -1 if not found • Keep in mind substring first you want, first you don’t want. • Also, there is a substring with only one argument, starts at that char and goes to end • substring probably a better idea that charAt, since chars not in subset

  41. Priority Queues public interface PriorityQueue { // postcondition: returns true if the number of elements in // the priority queue is 0; otherwise, returns false boolean isEmpty(); // postcondition: x has been added to the priority queue; // number of elements in the priority queue is increased by 1 void add(Object x); // postcondition: The smallest item in the priority queue is removed // and returned; the number of elements in the priority queue // is decreased by 1 // throws an unchecked exception if the priority queue is //empty Object removeMin(); // postcondition: The smallest item in the priority queue is returned; the //priority queue is unchanged //throws an unchecked exception if the priority queue is empty Object peekMin(); }

  42. Implementing P Queues • All items in a priority queue must implement __________________ • There are many ways to implement a priority queue • The most interesting to me is with a Heap • A heap is _________________________________ • The root contains the smallest element therefore removeMin is O(___) • Then the heap must be reheaped which is O(____) • This is cool

  43. MBCS • The MBCS consists of interfaces • Environment • Locatable • EnvDisplay • Classes(Visible) • Simulation • Fish • DarterFish • SlowFish • SquareEnvironment(Abstract) (Ch 5 – A/B only) • BoundedEnv • UnBoundedEnv • Classes(Black Box) • Debug • Direction • Location • RandNumGenerator

  44. MBCS • To Start • A program will create an environment and a display and then either • Add the fish manually one at a time or • ____________________________________ • Then a program will create a environment Display • A Simulation Object is created and the Environment and environment display are passed to it • Simulation asks the Environment for a list of Fish • What is the order of the fish in the array? • Locatable[] theFishes = theEnv.allObjects(); • for (int index = 0; index < theFishes.length; index++) • ( (Fish) theFishes[index]).act();

  45. MBCS • Valid Example Files (Empty file OK, two fish in same loc == joo got a problem, esse) bounded 10 10 Fish 0 0 North Fish 0 1 South Fish 0 2 East Fish 0 3 West Fish 0 4 North Fish 0 5 South Fish 0 6 East Fish 0 7 West Fish 0 8 North unbounded DarterFish 5 5 North DarterFish 3 3 South DarterFish 10 10 East DarterFish 6 8 West DarterFish 2 10 North DarterFish 1 1 South

  46. MBCS • BoundedEnv • Stores fish in what type of data structure?_____________________________________ • Fish ask to be added to the environment from their initialize method • When does BoundedEnv reject the fish’s request? • ______________________________________ • public void recordMove(Locatable obj, Location oldLoc) • records the move by updating the array if it was valid • sets the old location in the array to ______________

  47. MBCS • UnBoundedEnv • Uses an ArrayList called objectList • protected int indexOf(Location loc) //This method will get the index of where a fish living at loc is stored in the ArrayList or –1 if loc has no fish living there • Example • Fish at 0,4 6,3 and 6,5 • objectList = (0,4), (6,3), (6,5) • env.indexOf(new Location(6,5)) returns 2 • returns –1 for numRows() and numCols() • A/B’ers should look this over this weekend

  48. MBCS • Fish • Is there a direction that a fish cannot move in? • ________________________________ • Where is this accomplished?_____________________ • private void initialize(Environment env, Location loc, Direction dir, Color col) • fish use this to set initial values • public void act() //(with breeding and dying turned on) • Use isInEnv to see if fish is alive in env and where it thinks it is • Try to breed by calling breed method (default prob is 1/7) • Find any empty neighbors • Fill them with child fishes (same color as parents) • This is not the way it works in real life, boys, in case you fell asleep in health!!!!

  49. MBCS • public void act() //continued • If the fish did not breed, try to move by calling the move method (nextLocation plays a big role here) • Change the fish’s direction to the direction they just moved • Obtain a random object to see if this fish will die in this timestep • Default probability is ___________

  50. MBCS • Darter Fish • extends fish, overrides generateChild, nextLocation, move • How does a da’ta move? • _______________________________________ • SlowFish • extends fish, overrides generateChild and nextLocation • How does a slow fish move? • ________________________________________ • Polymorphism, late binding, cool stuff

More Related