OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Advertisements

Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.
Java Unit 9: Arrays Declaring and Processing Arrays.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 8 Single-Dimensional Arrays. Topics Declaring and Instantiating Arrays Accessing Array Elements Writing Methods Aggregate Array Operations Using.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 3 GEORGE KOUTSOGIANNAKIS Copyright: Illinois Institute of Technology/George Koutsogiannakis 1.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Chapter 9 Multidimensional Arrays and the ArrayList Class.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 4_1 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
Applications Development
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CS 116: Object Oriented Programming II. Topics Vectors Multidimensional Arrays ArrayList.
CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 3 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer 1.
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 6_1 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
The need for Programming Languages
Objects as a programming concept
Chapter 7 User-Defined Methods.
3 Introduction to Classes and Objects.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 15 GEORGE KOUTSOGIANNAKIS
Yanal Alahmad Java Workshop Yanal Alahmad
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
OBJECT ORIENTED PROGRAMMING II LECTURE 2_1 GEORGE KOUTSOGIANNAKIS
Java Review Hello..This ppt is to give you an introduction about java and why it is soo special The segments all discussed here are the crucial parts of.
INPUT STATEMENTS GC 201.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
An Introduction to Java – Part I, language basics
Classes & Objects: Examples
Defining methods and more arrays
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS
Building Java Programs
OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Arrays in Java.
CS201 Fall 2016 George Koutsogiannakis
Suggested self-checks: Section 7.11 #1-11
CMPE212 – Reminders Course Web Site:
CSC 111 Exam 3 Review Fall 2005.
Review for Midterm 3.
Week 7 - Monday CS 121.
Presentation transcript:

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

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

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

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

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.

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

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

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.

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

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.

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.

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.

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

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).

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

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

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

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];

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

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]);

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

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

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);

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

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

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.

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:

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)