comp-202: foundations of programmingcs202/2015-05/web/lectures/lecture8_obj… · midterm review...
TRANSCRIPT
COMP-202: Foundations of Programming
Lecture 8: Object Oriented Concepts and
Midterm Review
Sandeep Manjanna, Summer 2015
Announcements
• Midterm on 4th of June at 12:35 – 14:35.
• Exam rooms : Last Name Room
A – M BURN 1B45
N – Z BURN 306
• You are allowed one double-sided 8.5"x11" (letter-sized)
crib sheet. Please also bring pencils for the scantron, and
your McGill ID.
• Do not bring valuables, as you will be asked to leave your
bags at the front of the room.
This Lecture
� Sorting
� Object Oriented Concepts
� Classes and Objects
� Midterm Review
One step at a time….
Sorting
• As a review for Methods, we will implement one of the important applications of programming.
SORTING
• Given an array of numbers, arranging them according to some rule,
Ex: Ascending Order
Descending Order
• There are many algorithms to sort the given list,
Bubble sort
Insertion sort
Merge sort
Intuition for Bubble Sort
• Let the array length be N, and assume we are sorting the array in ascending order.
• We will go through the array N times:
We keep swapping adjacent elements of the array that are in the wrong order.
Gradually, all the largest elements will end up at the end of the array.
• After at most (N – 1) passes through the array, it will be sorted.
"Bubble" Sort
Like bubbles in a carbonated beverage rising to the top of the glass, the larger elements in the array gradually move to the end.
Explanation by Example
5 3 2 1 4 6
3 5 2 1 4 6
3 2 5 1 4 6
3 2 1 5 4 6
3 2 1 4 5 6
3 2 1 4 5 6
2 3 1 4 5 6
2 1 3 4 5 6
End of first pass through array
Cont'd
2 1 3 4 5 6
2 1 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
done!
End of second pass
End of third pass
End of fourth pass
End of fifth pass
Pseudo-code
Input: arr of length N
for iter = 0 … N - 2 // note range is inclusive
for i = 0 … N - 2 – iter // ignore the sorted elements
if (arr[i] > arr[i + 1]): // out of order
swap(arr, i, i + 1)
More Efficient
• During a pass, we can keep track of whether we've made a swap.
• If we haven't made any swap, we are done! (Everything is in order)
• If we did swap, keep going.
More Efficient Pseudo-code
Input: arr of length N
for iter = 0 … N - 2:
swapped = false
for i = 0 … N - 2 - iter:
if (arr[i] > arr[i + 1]):
swap(arr, i, i + 1)
swapped = true
if (!swapped):
break // break out early
Object Oriented Programming
Scalability
• Recall the Tic-Tac-Toe Game we programmed in previous class.
• The game is simple enough that our current strategy works:
• Pass in a char[][] to every method that needs to use the game board.
• But this is not scalable
• As complexity grows, this becomes too cumbersome. Need a new strategy!
• e.g., suppose we have multiple game boards, or many items that we need to manipulate
Creating a complex game like first person shooter
What do we need to store?double playerXLocation;
double playerYLocation;
double playerZLocation;
int gunType;
int bulletsLeft;
double lifeLeft;
double playerVelocityX;
double screenLeftX;
boolean[] enemiesOnScreen;
boolean[] enemiesAreAlive;
double[] buildingsXLocation;
double[] windowsInBuildingXLocation;
Too much information to pass around!
And that is just for starters. We also would need to store things like:
a)Location/velocity of all bullets, tanks, objects you can pick up, etc
b)Whether the game is paused
c)What sound should be playing
d)Testing to see what buttons the user hit on the keyboard/controller
e)Clouds in the sky
etc.
What do we need to store?
Now, let's write the main method for this.
We can use top-down programming to help us a bit.
public class Comp202FPS {
public static void main(String[] args)
{
boolean isPaused = checkIfPaused();
if (isPaused) {
displayMenu();
}
else {
playGame();
}
}
}
What do we need to store?
public static void playGame() {
while (!testIfUserHitsKey(spacebar)) {
displayGraphics();
getUserInput();
updateUserPosition();
updateObjectPositions();
playMusic();
checkIfUserDied();
}
}
What do we need to store?
This actually works fairly well as a way to plan things. However, when we start coding this in more detail, we will realize that each one of these methods needs a lot of information!
There are too many variables to keep in our head. It's very easy to mix up which variable does what.
Let's say we want to add extra features, for example add a new kind of armour. It's really hard to do this because we'll have to edit our playGame() method which is super huge!
Problem!!
Object Oriented Programming
In Object Oriented Programming, we will define a class or a new type, which is a blueprint for what an Object of that type will be.
These objects will consist of both data and methods that use the data.
Goal of Object oriented programming
• The goal of creating these objects is to allow us to group all relevant data together.
• In this way, we will not have to keep track of as many things at once.
• In the same way that arrays allow us to store several data values of the same type into one structure, these new types will allow us to store hundreds of different typed values into one data structure
Goal of Object oriented programming
Roughly speaking, object oriented programming allows you to do 2 things:
1) Group common data together.
2) Create methods that have access to this common data.
Roughly speaking
Classes
• A blueprint for a type of object, including:
Data Information relevant to this class
Methods Behaviours related to this class
• Objects are instances of classes that fit this blueprint.
String
• String is actually a class in Java. Every time you create a String object, you are creating an instance of class String.
String newString = "This is a String instance";
Data the sequence of characters
Methods .equals(), .length(), etc.
• Strings are special because there is special syntax related to creating them, printing them, etc.
StudentData:
int studentId;
String name;
double[] grades;
Course[] coursesTaken;
Methods:
double computeCGPA();
void addCourse(Course course);
An instance would represent one particular student.
Ex: Student x = new Student( );
For example, in our FPS, we could group much of our data together:
-Player (stores location, velocity, life, backpack, name)
-Enemy (stores location, velocity, life, backpack)
-Building (stores location, size, windowLocations)
-Sound (stores mp3 data, current note)
-Graphics (stores what part of the world is on screen)
-GameController (stores whether it's the menu or game displaying)
Back to our FPS
Now in our main program, we will not need to create nearly as many variables.
Player hero;
Enemy[] villains;
Building[] buildings;
Graphics renderer;
Sound audioPlayer;
Each one of these variables will then be responsible for maintaining its own state.
Back to our FPS
Midterm Review
Exam Format
• Multiple Choice questions. Bring Pencil to fill on Scantrons.
• 4 Sections :
• True or False Questions
• Fill in the missing statements
• What’s the Output?
• Code the Method
Concepts
• What is an algorithm?
• Programming vs natural language
• Different kinds of errors and examples:
Syntax, compiler
Run-time
Logic
Java bytecode
compilerprocessor
instructions
JVM
Evaluating Expressions
• Implicit conversions in data types:
5 + 4.0
• Order of operations and casting:
3 + 4 * (double) 2
"Hello " + 3 + 4
3 + 4 + " Hello"
Booleans
&&, ||, !
Be able to evaluate expressions by hand
e.g., A && (B || !A)
What if A = true, B = false?
Is it possible to come up with an assignment for A and B such that this expression evaluates to true?
Loops
• Get good at counting numbers of iterations that a loop runs.
What will the following code print?
int count;
for (count = 8; count > 1; count--){
count++;
System.out.print(count + " ");
}
It will go on printing 9 9 9 9 9 9 ……. (Infinitely)
Infinite Loop!!!
Arrays
• What are the key characteristics of arrays?
public static void createArray(int[] arr) {
arr = new int[15];
}
In main method:int [] a = {3, 5, 6};
createArray(a);
How About This?
public static void changeArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = 0;
}
}
In main method:int [] a = {3, 5, 6};
changeArray(a);
Methods
Understand:
the syntax of a method declaration
how to read Java Standard Libraries
how to call a method
how to pass values to a method
how to return a value from a method.
What would be the signature of a method myfunc() that :
1. Has a double array as a formal parameter
2. Returns an array of integers.
A. public void myfunc(double[] a)
B. public [] myfunc(double a)
C. public int myfunc(double a)
D. public int[] myfunc()
E. public int[] myfunc(double[] a)
Answer : E
Write a method to take an integer array ( x ) as argument and create its duplicate array
(res). The method should return the duplicate array. (Choose all possible answers)
Line 1:A. public static void createArray(int[] x)
B. public static int createArray(int[] x)
C. public static int createArray(int x)
D. public static int [] createArray(int[] x)
E. public static double [] createArray(int[] x)
Answer : D
Line 2:A. String[] res = new int[x.length];
B. int[] res = new int[x];
C. int[] res = new int[x.length];
D. int res = new int[x.length];
E. int[] res = x;
Answer : C
Line 3:A. for(int i=0; i < res.length; i++) { res[i] = x[i]; }
B. for(int i=0; i < res; i++) { res[i] = x[i]; }
C. for(int i=0; i < x.length; i++) { res[i] = x[i]; }
D. for(int i=0; i < res.length; i++) { res = x; }
E. for(int i=1; i < res.length; i++) { res[i] = x[i]; }
Answer : A and C
Line 4:A. return;
B. return res;
C. return res[i];
D. return x;
E. return x[i];Answer : B
Summary
� Sorting
� Object Oriented Concepts (Just Introduction)
� Midterm Review