Presentation is loading. Please wait.

Presentation is loading. Please wait.

OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS

Similar presentations


Presentation on theme: "OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS"— Presentation transcript:

1 OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
CS 201 OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS Copyright: Illinois Institute of Technology/George Koutsogiannakis

2 OOP Review In previous lecture we discussed:
Service classes versus Client classes. Packaging of classes using Command Line. Input using Command Line arguments. How to read text files with scanner object. The scope of a variable. Enumerations. Using the StringTokenizer object. Formatting of Numbers. Arrays

3 Arrays – Single Dimension Topics in Today’s Lecture
Review Material Declaring and Instantiating Arrays Entering Array Elements Accessing Array Elements Aggregate Array Operations Arrays of Objects. Using Arrays in classes. New Material Creating packages

4 Arrays An array is a sequence of variables of the same data type. Arrays are useful for many applications, including calculating statistics or representing the state of a game. The data type can be any of Java's primitive types (int, short, byte, long, float, double, boolean, char), an array, or a class. Each variable in the array is an element. We use an index to specify the position of each element in the array. An array is an Object by itself. Remember that we can also have arrays of objects. The objects can be representative of pre defined classes (library classes) or user defined classes

5 Declaring and Instantiating Arrays
Arrays are objects, so creating an array requires two steps: declaring a reference to the array instantiating the array To declare a reference to the array, use this syntax: datatype [] arrayName; To instantiate an array, use this syntax: arrayName = new datatype[ size ]; where size is an expression that evaluates to an integer and specifies the number of elements.

6 Examples Declaring arrays: Instantiating these arrays:
double [] dailyTemps; // elements are doubles String [] cdTracks; // elements are Strings boolean [] answers; // elements are booleans Auto [] cars; // elements are Auto references int [] cs101, bio201; // two integer arrays Instantiating these arrays: dailyTemps = new double[365]; // 365 elements cdTracks = new String[15]; // 15 elements int numberOfQuestions = 30; answers = new boolean[numberOfQuestions]; cars = new Auto[3]; // 3 elements cs101 = new int[5]; // 5 elements bio201 = new int[4]; // 4 elements

7 Default Values for Elements
When an array is instantiated, the elements are assigned default values according to the array data type. Array data type Default value byte, short, int, long float, double 0.0 char space boolean false Any object reference (for example, a String) null

8 Example array of integers
int [ ] myarray=new int[5]; The array size is 5 and the index will run from 0 to 4. index 1 2 3 4 Notice that initial values are 0 s since the array was declared to be an array of integer data types.

9 Assigning Initial Values to Arrays
Arrays can be instantiated by specifying a list of initial values. Syntax: datatype [] arrayName = { value0, value1, … }; where valueN is an expression evaluating to the data type of the array and is the value to assign to the element at index N. Examples: int nine = 9; int [] oddNumbers = { 1, 3, 5, 7, nine, nine + 2, 13, 15, 17, 19 }; Auto sportsCar = new Auto( "Ferrari", 0, 0.0 ); Auto [] cars = { sportsCar, new Auto( ), new Auto("BMW", 100, 15.0 ) };

10 Instantiating an Array
Or you can declare and then instantiate the array by indicating its size and then enter values one at a time i.e double [] myarray; myarray=new double[10]; Where 10 is the size of the array myarray.

11 Entering Array Elements
Enter an element in a specific index location. Suppose that we want to enter the number 10 in the position with index=2 in the array myintarray int [] myintarray=new int[5]; myintarray[2]=10; We can of course fill the array with multiple element values by using a for loop.

12 Entering Array Elements
i.e. for (int a=0 ; a<=myintarray.lenght-1; a++) myintarray[a]=(a+2); This loop enters the int values of a+2 into the array myintarray.

13 Entering Array Elements
Array Index Value entered 2 1 3 4 5 6

14 Accessing Array Elements
Array elements can be accessed by first declaring a data type variable similar to the data types held in the array and assigning the array element to that data type. i.e. int x; x=myarray[2]; the element in index position 2 is assigned to x (i.e x=4 from previous slide).

15 Calculating a Total Example This code calculates the total value of all elements in the array myintarray, which has previously been instantiated: int total = 0; // initialize total for ( int i = 0; i <= myintarray.length-1; i++ ) { total += myintarray[i]; } System.out.println( "The total is " + total ); The output should be: The total is 20 See Text Example 8.5 SummingArrayElements.java

16 Instantiating an Array of Objects
To instantiate an array with a class data type: 1. instantiate the array (elements are object references, initialized to null) 2. instantiate the objects Example: // instantiate array; all elements are null Auto [] cars = new Auto[3]; // instantiate objects and assign to elements Auto sportsCar = new Auto( "Miata", 100, 5.0 ); cars[0] = sportsCar; cars[1] = new Auto( ); // cars[2] is still null See Text Example 8.2 AutoArray.java

17 Example of Arrays of Objects
Suppose we have a Person service class with attributes: public class Person { String firstName=“ “; String lastName=“ “; int currentID=0; static int id=0; public Person(String fn, String ln) setFirstName(fn); setLastName(ln); id++; currentID=id; } Followed by accessor /mutator and toString methods. NEVER INCLUDE THE id ATTRIBURES IN THE LIST OF ARGUMENTS OF THE CONSTRUCTOR1111

18 Arrays of Objects Suppose the following class uses the class Person. We want to create 50 person objects and store them in an array : public class CreatePersons { public static void main(String[] args) { //for each of the instance variable we create an array. String Fname=“ “; String Lname=“ “; //create (instantiate) an array of type Person to hold 50 Person objects. // Although we fixed the size to 50 in this example in most cases the size will //be determined programmatically from the data in the text file that has the data. Person [] personArray=new Person[50];

19 Arrays of Objects //create 50 Person objects and place them in the array personArray for (int i=0; i<=personArray.length-1; i++ ) { FName="p"+i; LName="Doe"+i; personArray[i]=new Person(FName, LName); }

20 Arrays of Objects //Now output the ids and the Person objects attributes (instance variables) for each Person object in the array. for (int j=0; j<=personArray.length-1; j++) { System.out.println(" the id of each object is:"+" "+personArray[j].getCurrentID()); System.out.println(“The attributes of each object are:”+” “+personArray[j].toString()); } NOTE : calling the toString method in the above program is optiona, the same result will be accomplished if the code was written: System.out.println(“The attributes of each object are:”+” “+personArray[j]);

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

22 Methods with Array Parameters or Array return values
To define a method that takes an array as a parameter, use this syntax: accessModifier returnType methodName( dataType [] arrayName ) i.e. public int myMethod( Person [] aPersonArray) To define a method that returns an array, use this syntax: accessModifier dataType [] methodName( parameterList ) i.e public Person [] myMethod (String [] aStringsArray) Returned value data type Method argument data type

23 Methods with Array Parameters or Array return values
To pass an array as an argument when calling a method, use the array name without brackets: i.e. in the following call the method returns an array. We need to have an array of the data type for the array inatsntiate dto capture the returned array from the method call: Person [] mynewPersonArray=new Person[50]; mynewPersonArray=myMethod(stringArray);

24 Arrays as 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]; }

25 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; }

26 Finding min max Value in an array of numbers.
Suppose that we have an array of numeric data type like int. We need to develop an algorithm for finding the first instance of the maximum number stored in the array (it is possible that the same max number appears more than once in the array.

27 Finding min max Value in an array of numbers.
Suppose that I have the array: int [] intarray=new int[20]; //Let us declare a variable called max int max=0; //Let us iterate through the elements of the array and for compare each element to the max variable’s number. //If we find an element with a value greater than the value held by max then assign the value of that element to max and continue with the next comparison //In the example code given next we also capture the index at which the element with the maximum value was found:

28 Finding min max Value in an array of numbers
int indexOfmax=0; for(int i=0; i<=intarray.length-1; i++) { if(max<intarray[i]) max=intarray[i]; indexOfmax=i; } To find the minimum value all we have to do is to reverse the inequality sign in the if selection if(min>intarray)


Download ppt "OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS"

Similar presentations


Ads by Google