Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 3 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer 1.

Similar presentations


Presentation on theme: "CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 3 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer 1."— Presentation transcript:

1 CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 3 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer 1

2 OOP Review In previous lectures we discussed: – Scanner Class – Scope of a variable – Enumeration datatype – Packaging of classes using Command Line 2

3 Topics in Today’s Lecture Wrapper Classes (Textbook pg. 47, 150-153) Reading user input (Textbook pg. 505-506, 128-136) Arrays – Single Dimension (Textbook pg. 466-511) – Declaring and Instantiating Arrays – Entering Array Elements – Accessing Array Elements – Aggregate Array Operations – Arrays of Objects. – Using Arrays in classes. – Algorithms Finding Min and Max in an array Sequential search in an array 3

4 WRAPPER CLASS 4

5 Primitive Data Types 5 primitive integral booleanfloating point float double byte char short int long Note: A String is not a primitive data type but rather a pre defined class object

6 Wrapper Classes We can always convert a String to a primitive data type using classes called “Wrapper classes”. “Wrap” the value of a primitive data type into an object Useful when methods require an object argument Also useful for converting Strings to an int or double 6

7 Wrapper Classes Primitive Data TypeWrapper Class doubleDouble floatFloat longLong intInteger shortShort byteByte charCharacter booleanBoolean 7

8 Using Wrapper Classes import java.util.Scanner; import java.io.File; import java.io.IOException; public class ReadFile { public static void main(String[] args) { String str=" "; int sum=0; try { File myFile=new File("test.txt"); Scanner scan=new Scanner(myFile); while(scan.hasNextLine()){ str=scan.nextLine(); String []tok=str.split(“,"); for(int i=0; I < tok.length; ++i){ sum=sum + Integer.parseInt(tok[i])); } System.out.println(“Total: “ + sum); } catch(IOException ioe){ System.out.println("The file can not be read"); } 8 Method declaration from Integer Class API: public static int parseInt(String s)

9 ACCESSING USER INPUT 9

10 RECEIVING INPUT Different ways to read input into our programs: – User provides input via Command Line when the java interpreter is called. – Read user provided input via the keyboard using the Scanner object during execution (interpretation) of the program – Read a text file using the Scanner object (see Lecture 1). 10

11 Command Line Input Command line implies that: – A DOS window is opened (cmd command from start menu or assecories->command prompt) – The command line path is pointing to the path where the java program file (the one with the main method) is located. 11

12 Command Line Input We can obtain input data for a program from the DOS window when we use the interpret command. This is called “command line “ input. i.e some path…………>java StudentClient arg1 arg2 arg3 Where arg1 arg2 arg3 are the 3 pieces of data (in this example) that will be read as individual Strings by the main method of the program. 12

13 Command Line Input This approach is only good as long as the class has a main method. The String array argument of the main method captures the values entered by the user. There is no pre determined number of data values that the user can enter from the command line. 13

14 Command Line Input 14 public class Persons { String firstName; String lastName; int age; static int id; int currentid; public Persons(){ this.firstName="John"; this.lastName="nonone"; this.age=21; Persons.id++; this.currentid=id; } public Persons(String fName, String lName, int age){ this.firstName=fName; this.lastName=lName; this.age=age; Persons.id++; this.currentid=id; } public String toString(){ return "Last name: " + this.lastName + " Age: " + this.age; } public class PersonsClient { public static void main(String[] args) { Persons p1=new Persons(); //get the details for p2 from command line String fName = args[0]; String lName = args[1]; int age = Integer.parseInt(args[2]); Persons p2=new Persons(fName, lName, age); System.out.println("Person p2: " + p2.toString()); } args[0], args[1], args[2] store inputs from command line

15 Command Line Input Parameters to the Main() is a String array args From example, args[0], args[1], args[2] now have the values that the user entered: i.e. >java personsClient Jacob John 23 thus: args[0] has the value Jacob as a String args[1] has the value John as a String args[2] has the value 23 as a String 15

16 Command Line Input If we wanted to do arithmetic operations with the String versions of values 23 then we have to parse the String args[2] by using the appropriate wrapper class i.e int age= Integer.parseInt(args[2]); results in the int version of the String 23 (int age=20) You should use appropriate wrapper classes to convert the user input to particular data types. 16

17 Input Using the Scanner Class Sometimes we need to be able to capture input from the user while the program is running.. One way of providing input to the program is via the keyboard. A DOS window is required. Program should be interpreted from command line. The Scanner library class provides the functionality to allow us to capture keyboard input (and also read input from a file—we will cover the file reading later) Scanner class is part of the Library package java.util – Therefore we have to import the Scanner class 17

18 Receiving Input from the User Using the Scanner library class. Sometimes we need to prompt the user during the execution of the program so that input is provided after a specific set of instructions has been executed. – The previous technique of making the input part of the command to start the execution WILL NOT work then. We can provide this functionality by using the Scanner library class. The user can be prompted to enter data, after the program starts execution, via the keyboard. The Scanner object will read the characters typed on the keyboard. 18

19 Input Using the Scanner Class Scanner class provides methods for reading byte, short, int, long, float, double, and String data types from the Java console (keyboard) and other sources (like a file). Scanner parses (separates) input into sequences of characters called tokens. By default, tokens are separated by standard white space characters (tab, space, newline, etc.) i.e in the String “My name is Joe” there are 4 tokens. The first token is the substring “My” and so on. 19

20 A Scanner Constructor Scanner( InputStream source ) creates a Scanner object for reading from source. If source is System.in, this instantiates a Scanner object for reading from the Java console (keyboard). (System.in is the keyboard) Example: Scanner scan = new Scanner( System.in ); scan then is the object that we are going to use to read characters from the keyboard if System.in has been passed to the constructor of the Scanner class. The Scanner class has methods that help us capture the user ‘s input (as an example from the keyboard or a file). 20

21 Scanner Example Suppose that we want to read a String that a user of our program enters on the keyboard: 1. import java.util.Scanner; 2. class UsingScanner 3. { 4. public static void main(String[] args) 5. { 6.Scanner scan =new Scanner(System.in); 7.System.out.println("Enter a decimal number"); 8.String a=scan.next(); 9.double d=Double.parseDouble(a); 10.System.out.println(d); 11.} 12. } 21

22 Prompting the User On the DOS window we will see: C:\>java UsingScanner Enter a Decimal Number: _ After the user enters a number (let us say that the user typed the number 19.1) and presses the Enter key, the program resumes execution and line 9 is executed. Line 9 reads what the user typed (19.1) as a String and at the same time converts it into a double data type. It assigns that data type (stores in memory) to the identifier age in this example. From there on the program continues with the execution of other instructions. It is possible that we may want to stop the program further down again and ask the user to enter another input. 22

23 Scanner Example In the program the line: String a=scan.next(); captures whatever the user typed as a String data type (even if the user typed a number!) Our program converts the data type String represented by the identifier a to a double data type via the line: double d=Double.parseDouble(a); 23

24 Scanner Example Interpreting this program has the following outcome: C:>java UsingScanner Enter a decimal number 19.1 The number you entered is:19.1 Notice that after the statement “Enter a decimal number” is displayed, the program waits for the user to enter something on the keyboard. Notice that the next action is for the user to type 19.1 on the keyboard. The program then prints the last statement “The number you entered is:19.1” 24

25 SINGLE DIMENSIONAL ARRAYS 25

26 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), 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. Java implements arrays as Objects. Remember that we can also have arrays of objects. The objects can be representative of pre defined classes (library classes) or user defined classes 26

27 Declaring and Instantiating Arrays Arrays are objects, so creating an array requires two steps: 1.declaring a reference to the array 2.instantiating the array Array Declaration; – Specify the datatype and name of the variable – To declare a reference to the array, use this syntax: datatype [] arrayName; – Don’t need to know the size and/or values of the elements of the array 27

28 Declaring and Instantiating Arrays Array Instantiation: – Allocation of memory for array – Need to know atleast the size(no. of elements) of the array – Initial values can be assigned at this point – To instantiate an array, use this syntax: arrayName = new datatype[ size ]; size is an expression that evaluates to an integer and specifies the number of elements. 28

29 Examples Declaring 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 29

30 Array Declaration and Instantiation Array declaration and instantiation can be done simultaneously – Use the following syntax datatype [] arrayname = new datatype [size]; – Examples double [] height = new double [10]; String [] names = new String [x+y]; //where x and y are int 30 If x and y are float?

31 Default Values for Elements When an array is instantiated, the elements are assigned default values according to the array data type. 31 Array data typeDefault value byte, short, int, long0 float, double0.0 charspace booleanfalse Any object reference (for example, a String) null

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

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

34 Entering Array Elements Insert an element in a specific index location in the following way 34 int [] myintarray=new int[5]; myintarray[2]=10; Multiple element values can be inserted using a loop (for, while loop). enter the number 10 in the position with index=2

35 Entering Array Elements Using for loop 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. 35 length is an attribute for array object Array IndexValue entered 02 13 24 35 46

36 Accessing Array Elements Use the array index to access specific 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. 36 int x; x=myarray[2]; the element in index position 2 is assigned to x Declaring a variable similar to the data types of the array to hold the value

37 Calculating a Total Example This code calculates the total value of all elements in the array myintarray, which has previously been instantiated: 37 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

38 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 38 // 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 Declare and instantiate array of objects Instantiate object and assign to array Auto [] cars = {new Auto( "Miata", 100, 5.0 ), new Auto( ), null} Declare and instantiate together

39 Example of Arrays of Objects Suppose we have a Person service class with attributes: 39 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.

40 Arrays of Objects Suppose the following class uses the class Person. We want to create 50 person objects and store them in an array: 40 public class CreatePersons { public static void main(String[] args) { String Fname=“ “; String Lname=“ “; Person [] personArray=new Person[50]; for (int i=0; i<personArray.length; i++ ){ FName="p"+i; LName="Doe"+i; personArray[i]=new Person(FName, LName); } for (int j=0; j<personArray.length; 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()); } Instantiate an array of type Person to hold 50 Person objects. For loop to instantiate objects Instantiate and assign objects Access objects in array

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

42 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) 42 Returned value data type Method argument data type

43 Methods with Array Parameters or Array return values To pass an array as an argument when calling a method, : Person [] mynewPersonArray=new Person[50]; mynewPersonArray=myMethod(stringArray); 43 From previous slide: public Person [] myMethod (String [] aStringsArray) Use the array string Array without brackets Instantiate an array of Persons objects to receive the values from the method

44 Arrays as Instance Variables // constructor public CellPhone( double [] bills ) { // instantiate instance variable array // with same length as parameter this.cellBills = new double [bills.length]; // copy parameter array to cellBills array for ( int i = 0; i < cellBills.length; i++ ) this.cellBills[i] = bills[i]; } 44 First instantiate an array for the instance variable Copy the values into the instance variable Can we not do this in the class declaration?

45 Arrays as Instance Variables // constructor public CellPhone( double [] bills ) { // instantiate instance variable array // with same length as parameter this.cellBills = new double [bills.length]; // copy parameter array to cellBills array for ( int i = 0; i < cellBills.length; i++ ) this.cellBills[i] = bills[i]; } 45 First instantiate an array for the instance variable Copy the values into the instance variable Can we not do this in the class declaration? We can, but need to know the size of the array

46 Accessors for Arrays 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; } 46 accessor method for the array instance variable should return a reference to a copy of the array.

47 Finding Min Max Value in an array of numbers. Suppose that we have an array of numeric data type int and need to find the Min or Max value or find the first 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). Algorithm design – What are our constraints? What is our basic operator? 47

48 Finding min max Value in an array of numbers. Algorithm Steps – Suppose that I have the array of integers: int [] intarray={4,2,5,6,7,8,9,23,45,6,7,34,56}; – Let us iterate through the elements of the array – Need to use a variable called max to hold our current maximum values int max=0; – Need to use a variable call index to hold the position in the array containing this maximum value int index=-1; – Compare each element to max 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 the index of the element to index Continue with the next comparison 48

49 Finding min-max Value in an array of numbers //finding maximum values and its index in an int array int index=-1; int max=0; int [] intarray={4,2,5,6,7,8,9,23,45,6,7,34,56}; for(int i=0; i<intarray.length; i++) { if(max<intarray[i]){ max=intarray[i]; index=i; } 49 What if the array had only negative integers?

50 Comparisons in Min-Max Algorithm Suppose you have an array of n elements How many comparison do you have to do to find the max and min? 50

51 Arrays – Single Dimension Topics Copying Array Values. Enumerations. Searching Arrays. Selection Sort. 51

52 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: 52 for ( int i = 0; i < cellBills.length; i++ ) { billsBackup[i] = cellBills[i]; } The effect of this for loop is shown on the next slide. See Example 8.7 CopyingArrayElements.java

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

54 Changing an Array's Size An array's length instance variable is constant – that is, arrays are assigned a constant size when they are instantiated To expand an array while maintaining its original values: 1.Instantiate an array with the new size and a temporary name 2.Copy the original elements to the new array 3.Point the original array reference to the new array 4.Assign a null value to the temporary array reference 54

55 Comparing Arrays for Equality To compare whether the elements of two arrays are equal: 1.Determine if both arrays have the same length 2.Compare each element in the first array with the corresponding element in the second array To do this, we'll use a flag variable and a for loop. 55

56 Comparing cellBills1 to cellBills2 boolean isEqual = true; // flag variable if ( cellBills1.length != cellBills2.length ) isEqual = false; // sizes are different else { for ( int i = 0; i < cellBills1.length && isEqual; i++ ) { if ( Math.abs( cellBills1[i] - cellBills2[i] ) > 0.001 ) isEqual = false; // elements are not equal } See Example 8.8 ComparingArrays.java 56

57 Algorithms An algorithm is a set of instructions that need to be followed and results in a predictable end-state from a given input. – We can program the instructions to achieve a specific result – For example, we may want to develop a technique for searching arrays to find if a specific piece of data is store din the array and in which index is stored. – Another example is the case where we want to store the values stored in an array in some predefined order. 57

58 Sequential Search A Sequential Search can be used to determine if a specific value (the search key) is in an array. Approach Start with the first element and compare each element to the search key: – If found, return the index of the element that contains the search key – If not found, return -1 Because -1 is not a valid index, this is a good return value to indicate that the search key was not found in the array 58

59 Code to Perform a Sequential Search Suppose we want to search array: int numbers[] for a number of value key: public int sequentialSearch ( int key ) { for ( int i = 0; i < numbers.length; i++ ) { if ( numbers[i] == key ) return i; } return -1; } 59

60 Example Suppose numbers={ 3, 5, 1, 6, 10, 2 } and key=6 i=0 is 6==3 ? No i=1 is 6==5 ? No i=2 is 6==1 ? No i=3 is 6==6 ? Yes return index=3 (found it) 60

61 Comparisons for Sequential Search Consider an array of size n – How many comparisons do you have to do? – Best case? – Worst case? 61


Download ppt "CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 3 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer 1."

Similar presentations


Ads by Google