Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.

Similar presentations


Presentation on theme: "CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis."— Presentation transcript:

1 CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis

2 Last Week’ s Topics Event-Controlled Loops Using do/while Count-Controlled Loops Using for Nested Loops Concept of Arrays. – Declaring and Instantiating Arrays – Accessing Array Elements 2

3 New Topics Copying arrays Using Arrays in Classes Arrays of Objects Probabilities Using Multiple Classes 3

4 Arrays In previous lecture we developed the concept of arrays. – Arrays are one of the many ways available to store a group of data in memory and identify that group of data under a unique name. The space required in memory has to be declared in advance before we start entering any data (that is a draw back sometimes because we don’t know in advance how much data we need to store) 4

5 Arrays – Since different data types require different amounts of memory i.e. an int requires 4 bytes, a double 8 bytes and so on We also need to identify in advance the data types that we are going to store in the array For example: Suppose that we need an array to store 10 int numbers. That means that 4*10 = 40 bytes of memory is needed. But what if we wanted to store 10 decimal numbers of double type? Tehn 8*10 = 80 byte sof memory is needed. – Therefore it is also a requirement to define the data type that the array will store when we define the size! 5

6 Arrays Thus, we first declare the size and type of the array before we use it to store data i.e. – int [] myarray=new int[20]; The above array under the name myarray is designated to hold 20 numbers of int type!! – Notice that the identifier for the array is (like any other identifier that we use for data types or objects) an address in memory where our dada is stored (the beginning address). 6

7 Copying Arrays Suppose we want to copy the elements of an array to another array, we could try the following code: double [] array1 = new double [6]; double [] array2: array2 = array1; // incorrect! Although this code compiles, it is logically incorrect! We are copying the array1 object reference (memory address) to the array1 object reference. We are not copying the array data. 7

8 Copying Array References The result of the code from the previous slide: billeBackup = cellBills; has this effect. Both references point to the same array. 8

9 Copying Array Values Example This code copies the values of all elements in an array named cellBills to an array named billsBackup, both of which have previously been instantiated with the same length: int [] cellBills= new int[size]; int [] billsBackup=new int[size]; for ( int i = 0; i < cellBills.length; i++ ) { billsBackup[i] = cellBills[i]; } The effect of this for loop is shown on the next slide. 9

10 Copying Array Values (cont’d) A separate copy of the array has been created. 10

11 Using Arrays in Classes In a user-defined class, an array can be: – an instance variable – a parameter to a method – a return value from a method – a local variable in a method 11

12 Methods with Array Parameters To define a method that takes an array as a parameter, use this syntax: accessModifier returnType methodName( dataType [] arrayName ) To define a method that returns an array, use this syntax: accessModifier dataType [] methodName( parameterList ) To pass an array as an argument when calling a method, use the array name without brackets: methodName( arrayName ) 12

13 Arrays as Instance Variables Because arrays are objects, the name of an array is an object reference ( an address in memory). Methods must be careful not to share references to instance variables with the client. Otherwise, the client could directly change the array elements using the reference to the array instance variable. 13

14 Array Instance Variables A constructor (or mutator) that accepts an array parameter should instantiate the instance variable array and copy the elements from the parameter array to the instance variable. // constructor public CellPhone( double [] bills ) { // instantiate instance variable array // with same length as parameter cellBills = new double [bills.length]; // copy parameter array to cellBills array for ( int i = 0; i < cellBills.length; i++ ) cellBills[i] = bills[i]; } 14

15 Accessors for Arrays Similarly, an accessor method for the array instance variable should return a reference to a copy of the array. public double [] getCellBills( ) { // instantiate temporary array double [] temp = new double [cellBills.length]; // copy instance variable values to temp for ( int i = 0; i < cellBills.length; i++ ) temp[i] = cellBills[i]; // return copy of array return temp; } 15

16 Arrays of Objects Suppose we have a template class as the one used in some of our labs (i.e People) Suppose that we want create in a client class 10 People objects and save them into an array. First we declare the array type People [] mypeoplearray; then we instantiate the array since we assume that we know the size. mypeoplearray=new People[10]; Now we are ready to enter (save ) People objects in this array. 16

17 Arrays of Objects People Objects are created first: People p1=new People(“Joe”, 1234, 5.5): People p2=new People(“Mary”, 3456, 5.6): People p3=new People(“Helen”, 5678, 5.4); …………………… e.t.c. ………………………………… Now let us insert the objects: mypeoplearray[0]=p1; mypeoplearray[1]=p2; mypeoplearray[2]=p3; …………….. e.t.c. ………………………………………… 17

18 Arrays of Objects Now let us retrieve the stored objects. We need People references to be created first that will capture the objects that we are retrieving from the array. People anotherp1= mypeoplearray[0]; People anotherp2=mypeoplearray[1]; …………….. e.t.c. ……………………………………… 18

19 Arrays of Objects We can use for loops to read arrays of objects and display the attributes of each object using the toString() method of the template class. for( int j=0; j<=mypeoplearray.length-1; j++) { System.out.println(mypeoplearray[j].toString()); } Writing : mypeoplearray[0].toString(); is the same as getting the object that is stored in the oth index of the array and calling its toString() method to get the values of its attributes. 19

20 Arrays of Objects Suppose a method is responsible for reading a file and creating People objects from the data in the file. The method belongs in a class called A. The method stores the People objects into an array of type People as it reads them. Finally it returns the array. The signature of the method could be: public People [] createArray(); 20

21 Arrays of Objects Now suppose that from another class, called B, and from a method called MyMethod () of class B, we want to order the method createArray (of class A) to read the file, create the array and return it to our method in class B. We would need to have an array of People type to capture the returned array from createArray method, when we make the call. Thus: People [] anotherarray; A obj=new A(); anotehrarray=obj.createArray(); 21

22 Arrays of Objects Example of calling an accessor method of an object that is stored in an array: Suppose we inserted the object p1 in an array of People type. mypeoplearray[0]=p1 (where p1 is a People type object) Accessing the accessor method getPersonID () of People class (which returns an int): int id=mypeoplearray[0].getPersonID(); is the same as if we had written: int id=p1.getPersonID(); 22

23 Probability Density Functions In the project we need to use 3 different probabilities. Uniform Probability Distribution : – A number out of a range of numbers is produced every time we call the Math.random() method. The probabilty of producing a number is equal for all numbers in the range. – An example is the dice game. The range of numbers is 1 to 6. All 6 numbers have equal probability of occuring (1/6). – We use the following code to produce the numbers 1 to 6 int num =( int)(1+Math.random()*(6)); Every time we execute the above code we get a number capture d by the identifier num. The values for num will be from 1 to 6. i.e. If we call the execution of the line of code 10 times we may get: 2, 4, 1, 6, 1,,1, 3, 4, 1, 2. 23

24 24

25 Exponential Probability Distribution In this type of probability function the probability of getting a num is exponentially decaying as the numbers get larger. Smaller numbers have greater probability of occuring. We use the Math.random () call again but thie time the code is: int num = (int)(-5*Math.log(Math.random())); The number 5 in the above formula is the expected average of all the numbers produced after multiple executions. 25

26 26 Where lambda is the average of the Distribution.

27 Normal Probability Distribution This is the so called Bell curve. It represents various populations of events. For instance,the distribution of grades in a class of students. The numbers produced follow a probability that is haped like a bell (thus the name). We can generate numbers that have a certain average and standard deviation by using the following line of code: int num=(int)(5+(3*Math.cos(2*Math.PI*Math.random()))); The number 5 represents the average of all the numbers produced (provided we produce a large number of numbers) The number 3 represents the standard deviation. cos is the trigonometric function called cosine. 27

28 28 The average is zero in this Example. The standard deviation is 1. For example there is 40% Chance that the average will occur. There is 20% chance that -1 will Occur. 68.3 % of the population falls from -1 tp +1 (between the + or – of the standard deviation ) in this example.

29 Using Multiple Classes We can have multiple classes in our program. At least one of them must be the class that has a main method and determines the execution of the program. Thus far we used at most two classes (besides library classes): One that we called template and one that we used as a client to the template class. We could, however, as an example have multiple template classes. 29

30 Multiple Classes In your project you have three template classes (neither one has a main method): – People – Vehicles – Lottery – Notice that the above classes can have other methods besides the usual constructors, accessor and mutator methods. i.e. The Lottery class is also responsible for drawing a number based on the probability distribution function assigned to each type of casino. 30

31 Using Multiple classes In addition we could have two more classes that I would call “Helper Classes” to facilitate the reading of respective People and Vehicle information files (files with data about People and Vehicles). i.e CreatePeople and CreateVehicle classes. These helper classes also create respective People and Vehicle type arrays based on the information read and returned them to whoever calls them. Finally we could have a class called LoterySimulator that has a main method and controls the game. It is the job of this class to order the creation of the respective People and Vehicle Arrays and to proceed with the game including the race part. – We could, if we wanted, delegate the task of running the race to another helper class called Race which has methods that run the race and return the result. The LotterySimulator class will have to get the information of the vehicle that won the race from the Race class and display it. 31

32 Using Multiple classes There could be other ways to split the tasks. It is up to us to decide how the tasks get shared by the various classes and how many classes we are going to have. 32

33 Study Guide Chapter 8 – Section 8.3, 8.5 33


Download ppt "CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis."

Similar presentations


Ads by Google