370 likes | 498 Views
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) Decompose a problem into classes, define relationships and responsibilities of those classes. Program design.
E N D
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) • Decompose a problem into classes, define relationships and responsibilities of those classes
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
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 must implement all methods in the interface • Use extends and implements appropriately • declare constructors and methods with • meaningful names • appropriate parameters • appropriate return types (remember constructors do not have return types)
Class design • Class Design • appropriate declaration of methods as private or public • all data should be private
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
Program Implementation • Programming constructs • Primitives vs references • Remember that references must be associated with an object • Beware of aliasing:when two references point to the same object
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.
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
Method declarations • Method declarations • A method’s signature consists of name, parameter types and order of parameters • Overloaded methods have the same name but different parameters • Constructors are often overloaded • What is a static method?a method that does not require an instance of the class to be created • What is a private method?accessible only to class member methods
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
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” if (x.compareTo(y) < 0)
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)
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
For each loop used heavily • The for each loop will probably be used heavily in the exam • ArrayList<String> songs = some list • Write a for each loop to print the songs • int[] nums = some array of integers • Write a for each loop to find the average as a double
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
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
Data Structures • int : 32 bit signed integer • double: 64 bit signed floating point • boolean: true or false
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 _____________
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
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
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
Stacks • ______________ data structures • Good when you need to untangle some type of operations that have to be suspended and returned to
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(); }
GridWorld • GridWorld is an object oriented universe where Actors can be called on to act() each step • public Color getColor() { } • public void setColor(Color newColor) { } • public int getDirection() { } • public void setDirection(int newDirection) { } • public Grid getGrid() { } • public Location getLocation() { } • public void putSelfInGrid(Grid gr, Location loc) { } • public void removeSelfFromGrid() { } • public void moveTo(Location newLocation) { } • public void act() { } • public String toString() { }
GridWorld • Location represents a row, col (y,x) in the grid • For convenience, Location also has constants set up to handle the various directions • use getRow() and getCol() to get the y and x locations resepectively
GridWorld • public static final int LEFT = -90; • public static final int RIGHT = 90; • public static final int HALF_LEFT = -45; • public static final int HALF_RIGHT = 45; • public static final int FULL_CIRCLE = 360; • public static final int HALF_CIRCLE = 180; • public static final int AHEAD = 0; • public static final int NORTH = 0; • public static final int NORTHEAST = 45; • public static final int EAST = 90; • public static final int SOUTHEAST = 135; • public static final int SOUTH = 180; • public static final int SOUTHWEST = 225; • public static final int WEST = 270; • public static final int NORTHWEST = 315;
GridWorld • A BoundedGrid implements the Grid Interface • It uses a ____________________ called ______________to store the elements • private Object[][] occupantArray; // the array storing the grid elements • getNumRows() and getNumCols() will handle the dimensions
GridWorld • A BoundedGrid implements the Grid Interface • It uses a ____________________ called ______________to store the elements • private Object[][] occupantArray; // the array storing the grid elements • getNumRows() and getNumCols() will handle the dimensions • isValid(Location loc) is an important method to know • public boolean isValid(Location loc) • { • return 0 <= loc.getRow() && loc.getRow() < getNumRows() • && 0 <= loc.getCol() && loc.getCol() < getNumCols(); • }
GridWorld • public E get(Location loc) • { • if (!isValid(loc)) • throw new IllegalArgumentException("Location " + loc • + " is not valid"); • return (E) occupantArray[loc.getRow()][loc.getCol()]; // unavoidable warning • } • public E put(Location loc, E obj) • {} • public E remove(Location loc) • {}
GridWorld • Critters! • public void act() { } • public ArrayList getActors() {} • public void processActors(ArrayList actors) { } • public ArrayList getMoveLocations() { } • public Location selectMoveLocation(ArrayList locs) {} • public void makeMove(Location loc) { }
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
Math.random() All of the random() calls are made using Math.random() This gives you a number between _______ and ________Example, use Math.random() to generate a # for choosing and element from an ArrayList called locations
Sorting • Quadratic Sorts O(n2) • Selection • Choose the maximal or minimal element by a loop and then swap that with the current place you are moving through • Minimizes swaps • Insertion • Pick an element, shift everyone out of the way to make room for it (Church pew shuffle) • Bubble • Nested for loops allow one element to “bubble” to the front or back each time
Sorting • nlogn Sorts • Merge • Start breaking up your list into smaller lists and merge them together • Requires temporary storage area of size n for merging into
Thats all folks!!!! • Neo journeyed to the machine city and faced off with Smith • Frodo took the ring to the Mountain of Doom • On May 3, you will accomplish your mission, the APCS exam • It is your purpose!