Download presentation
Presentation is loading. Please wait.
PublishΑκακαλλις Κορνάρος Modified over 6 years ago
1
Basic Files + (Chapter 10 – Arrays) : Objectives
Intro to OOP with Java, C. Thomas Wu Basic Files + (Chapter 10 – Arrays) : Objectives After you have read and studied this chapter, you should be able to Understand reading from and writing to a text file Manipulate a collection of data values, using an array. Declare and use an array of primitive data types in writing a program. Declare and use an array of objects in writing a program Define a method that accepts an array as its parameter and a method that returns an array Describe how a two-dimensional array is implemented as an array of arrays Manipulate a collection of objects, using lists and maps We will cover the basic array processing in this lesson, manipulating arrays of primitive data types and objects. ©The McGraw-Hill Companies, Inc.
2
Sample Text file Input with Scanner
import java.io.*; class Ch12TestScanner { public static void main (String[] args) throws IOException { //open the Scanner Scanner scanner = new Scanner(new File("sample3.data")); //get integer int i = scanner.nextInt(); //similar process for other data types scanner.close(); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
3
Sample Text file Output
import java.io.*; class Ch12TestPrintWriter { public static void main (String[] args) throws IOException { //set up file and stream File outFile = new File("sample3.data"); FileOutputStream outFileStream = new FileOutputStream(outFile); PrintWriter outStream = new PrintWriter(outFileStream); //write values of primitive data types to the stream outStream.println( ); outStream.println("Hello, world."); outStream.println(true); //output done, so close the stream outStream.close(); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
4
Arrays of Primitive Data Types
Intro to OOP with Java, C. Thomas Wu Arrays of Primitive Data Types What is an Array? Why do we need them? Array Declaration <data type> [ ] <variable> //variation 1 <data type> <variable>[ ] //variation 2 Array Creation <variable> = new <data type> [ <size> ] Example double[ ] rainfall; rainfall = new double[12]; Variation 1 double rainfall [ ]; rainfall = new double[12]; Variation 2 As you can declare and create objects in one statement such as Person p = new Person( ); you can declare and create an array in one statement as double[ ] rainfall = new double[12]; Strictly speaking, an array is a reference data type and really an object because there is no class called Array in Java. The thumbnail note in page 413 is therefore not 100 percent accurate. An array is like an object! ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
5
Accessing Individual Elements
Intro to OOP with Java, C. Thomas Wu Accessing Individual Elements Individual elements in an array are accessed with the indexed expression. double[] rainfall = new double[12]; rainfall 1 2 3 4 5 6 7 8 9 10 11 rainfall[2] This indexed expression refers to the element at position #2 The index of the first position in an array is 0. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
6
Array Processing – Sample1
Intro to OOP with Java, C. Thomas Wu Array Processing – Sample1 double[] rainfall = new double[12]; double annualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showinputDialog(null, "Rainfall for month " + (i+1) ) ); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The public constant length returns the capacity of an array. This code computes the average annual rainfall. Notice the public constant length returns the capacity, not the actual number of non-blank values in the array. Reading input from command line public static void main (String args[]) –-- args[0], args[1] ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
7
Array Processing – Sample 2
Intro to OOP with Java, C. Thomas Wu Array Processing – Sample 2 double[] rainfall = new double[12]; String[] monthName = new String[12]; monthName[0] = "January"; monthName[1] = "February"; … double annualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showinputDialog(null, "Rainfall for " monthName[i] )); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The same pattern for the remaining ten months. This code also computes the average annual rainfall, but this time we use the second array, an arrray of String so the prompt becomes "Rainfall for January", "Rainfall for February", and so forth. Notice how the monthName array is used in the for loop. The actual month name instead of a number. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
8
Array Processing – Sample 3
Intro to OOP with Java, C. Thomas Wu Array Processing – Sample 3 Compute the average rainfall for each quarter. //assume rainfall is declared and initialized properly double[] quarterAverage = new double[4]; for (int i = 0; i < 4; i++) { sum = 0; for (int j = 0; j < 3; j++) { //compute the sum of sum += rainfall[3*i + j]; //one quarter } quarterAverage[i] = sum / 3.0; //Quarter (i+1) average This code computes the average rainfall for each quarter. The inner loop is used to compute the rainfall for a given quarter. The outer loop processes the four quarters. This is how the values for i, j, and 3*i+j change: i j 3*i+j 0 0 0 1 1 2 2 1 0 3 1 4 2 5 2 0 6 1 7 2 8 1 10 2 11 The sample code is equivalent to for (int i = 0; i < 3; i++ ) { quarterAverage[0] += rainfall[i]; quarterAverage[1] += rainfall[i+3]; quarterAverage[2] += rainfall[i+6]; quarterAverage[3] += rainfall[i+9]; } quarterAverage[0] = quarterAverage[0] / 3.0; quarterAverage[1] = quarterAverage[1] / 3.0; quarterAverage[2] = quarterAverage[2] / 3.0; quarterAverage[3] = quarterAverage[3] / 3.0; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
9
Intro to OOP with Java, C. Thomas Wu
Array Initialization Like other data types, it is possible to declare and initialize an array at the same time. int[] number = { 2, 4, 6, 8 }; double[] samplingData = { 2.443, 8.99, 12.3, , 18.2, 9.00, 3.123, , }; String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; When an array is initialized in this manner, its capacity is set to the number of elements in the list. number.length samplingData.length monthName.length 4 9 12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
10
Variable-size Declaration
Intro to OOP with Java, C. Thomas Wu Variable-size Declaration In Java, we are not limited to fixed-size array declaration. The following code prompts the user for the size of an array and declares an array of designated size: int size; int[] number; size= Integer.parseInt(JOptionPane.showInputDialog(null, "Size of an array:")); number = new int[size]; Instead of declaring the array size to a fixed value, it is possible to declare its size at the runtime. For example, we can prompt the user for the size of an array as illustrated in the sample code shown here. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
11
Intro to OOP with Java, C. Thomas Wu
Array of Objects Example : Person Class We will use Person objects to illustrate the use of an array of objects. Person latte; latte = new Person( ); latte.setName("Ms. Latte"); latte.setAge(20); latte.setGender('F'); System.out.println( "Name: " + latte.getName() ); System.out.println( "Age : " + latte.getAge() ); System.out.println( "Sex : " + latte.getGender() ); The Person class supports the set methods and get methods. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
12
Creating an Object Array - 1
Intro to OOP with Java, C. Thomas Wu Creating an Object Array - 1 Code Person[ ] person; person = new Person[20]; person[0] = new Person( ); A Only the name person is declared, no array is allocated yet. After is executed A person State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
13
Creating an Object Array - 2
Intro to OOP with Java, C. Thomas Wu Creating an Object Array - 2 Code Person[ ] person; person = new Person[20]; person[0] = new Person( ); Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. B person After is executed B 1 2 3 4 16 17 18 19 person State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
14
Creating an Object Array - 3
Intro to OOP with Java, C. Thomas Wu Creating an Object Array - 3 Code Person[ ] person; person = new Person[20]; person[0] = new Person( ); One Person object is created and the reference to this object is placed in position 0. C 1 2 3 4 16 17 18 19 person 1 2 3 4 16 17 18 19 person After is executed C Person State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
15
Person Array Processing – Sample 1
Intro to OOP with Java, C. Thomas Wu Person Array Processing – Sample 1 Create Person objects and set up the person array. String name, inpStr; int age; char gender; for (int i = 0; i < person.length; i++) { name = inputBox.getString("Enter name:"); //read in data values age = inputBox.getInteger("Enter age:"); inpStr = inputBox.getString("Enter gender:"); gender = inpStr.charAt(0); person[i] = new Person( ); //create a new Person and assign values person[i].setName ( name ); person[i].setAge ( age ); person[i].setGender( gender ); } The indexed expression person[i] is used to refer to the (i+1)st object in the person array. Since this expression refers to an object, we write person[i].setAge( 20 ); to call this Person object’s setAge method, for example. This is the syntax we use to call an object’s method. We are just using an indexed expression to refer to an object instead of a simple variable. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
16
Person Array Processing – Sample 2
Intro to OOP with Java, C. Thomas Wu Person Array Processing – Sample 2 Find the youngest and oldest persons. int minIdx = 0; //index to the youngest person int maxIdx = 0; //index to the oldest person for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < person[minIdx].getAge() ) { minIdx = i; //found a younger person } else if (person[i].getAge() > person[maxIdx].getAge() ) { maxIdx = i; //found an older person } //person[minIdx] is the youngest and person[maxIdx] is the oldest Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() > oldest.getAge() ) { oldest = person[i]; //found an older person outputBox.printLine("Oldest : " + oldest.getName() + " is " + oldest.getAge() + " years old."); outputBox.printLine("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old."); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
17
Object Deletion – Approach 1
Intro to OOP with Java, C. Thomas Wu Object Deletion – Approach 1 int delIdx = 1; person[delIdx] = null; Delete Person B by setting the reference in position 1 to null. A 1 2 3 person A B C D 1 2 3 person A C D Before is executed After is executed In this approach, we simply leave the position of a deleted object to a null. With this approach, an array index positions will be a mixture of null and real pointers. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
18
Object Deletion – Approach 2
Intro to OOP with Java, C. Thomas Wu Object Deletion – Approach 2 int delIdx = 1, last = 3; person[delIndex] = person[last]; person[last] = null; Delete Person B by setting the reference in position 1 to the last person. A 1 2 3 person A B C D 1 2 3 person A C D Before is executed After is executed With the second approach, we divide the array into two parts: the first part contains the real references and the second part contains the null references. When we delete a node, a hole will result and we must fill this hole. There are two possible solutions. The first solution is to pack the elements. If an object at position J is removed (i.e., this position is set to null), then elements from position J+1 till the last non-null reference are shifted one position lower. And, finally, the last non-null reference is set to null. The second solution is to replace the removed element by the last element in the array. The first solution is necessary if the Person objects are arranged in some order (e.g., in ascending order of age). The second solution is a better one if the Person objects are not arranged in any order. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
19
Person Array Processing – Sample 3
Intro to OOP with Java, C. Thomas Wu Person Array Processing – Sample 3 Searching for a particular person. Approach 2 Deletion is used. int i = 0; while ( person[i] != null && !person[i].getName().equals("Latte") ) { i++; } if ( person[i] == null ) { //not found - unsuccessful search System.out.println("Ms. Latte was not in the array"); } else { //found - successful search System.out.println("Found Ms. Latte at position " + i); Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() > oldest.getAge() ) { oldest = person[i]; //found an older person System.out.println("Oldest : " + oldest.getName() + " is " + oldest.getAge() + " years old."); System.out.println("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old."); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
20
Passing Arrays to Methods - 1
Intro to OOP with Java, C. Thomas Wu Passing Arrays to Methods - 1 Code A public int searchMinimum(float[] number)) { … } minOne = searchMinimum(arrayOne); At before searchMinimum A arrayOne A. Local variable number does not exist before the method execution When an array is passed to a method, only its reference is passed. A copy of the array is NOT created in the method. public int searchMinimum(float[] number) { int indexOfMinimum = 0; for (int i = 1; i < number.length; i++) { if (number[i] < number[indexOfMinimum]) { //found a indexOfMinimum = i; //smaller element } return indexOfMinimum; State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
21
Passing Arrays to Methods - 2
Intro to OOP with Java, C. Thomas Wu Passing Arrays to Methods - 2 Code public int searchMinimum(float[] number)) { … } B minOne = searchMinimum(arrayOne); arrayOne The address is copied at B number arrayOne B. The value of the argument, which is an address, is copied to the parameter. State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
22
Passing Arrays to Methods - 3
Intro to OOP with Java, C. Thomas Wu Passing Arrays to Methods - 3 Code public int searchMinimum(float[] number)) { … } C minOne = searchMinimum(arrayOne); arrayOne number While at inside the method C C. The array is accessed via number inside the method. State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
23
Passing Arrays to Methods - 4
Intro to OOP with Java, C. Thomas Wu Passing Arrays to Methods - 4 Code public int searchMinimum(float[] number)) { … } minOne = searchMinimum(arrayOne); D arrayOne number arrayOne At after searchMinimum D D. The parameter is erased. The argument still points to the same object. State of Memory ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
24
Two-Dimensional Arrays
Intro to OOP with Java, C. Thomas Wu Two-Dimensional Arrays Two-dimensional arrays are useful in representing tabular information. In Java, data may be organized in a two-dimensional array. A table is an example of a two-dimensional array. In a two-dimensional array, two indices (in a table, one for the row and one for the column) are used to refer to the array element. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
25
Declaring and Creating a 2-D Array
Intro to OOP with Java, C. Thomas Wu Declaring and Creating a 2-D Array Declaration <data type> [][] <variable> //variation 1 <data type> <variable>[][] //variation 2 Creation <variable> = new <data type> [ <size1> ][ <size2> ] Example 3 2 1 4 payScaleTable payScaleTable = new double[4][5]; is really a shorthand for payScaleTable = new double[4][ ]; payScaleTable[0] = new double[5]; payScaleTable[1] = new double[5]; payScaleTable[2] = new double[5]; payScaleTable[3] = new double[5]; which is equivalent to for (int i = 0; i < 4; i++) { payScaleTable[i] = new double[5]; } double[][] payScaleTable; payScaleTable = new double[4][5]; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
26
Intro to OOP with Java, C. Thomas Wu
Accessing an Element An element in a two-dimensional array is accessed by its row and column index. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
27
Sample 2-D Array Processing
Intro to OOP with Java, C. Thomas Wu Sample 2-D Array Processing Find the average of each row. double[ ] average = { 0.0, 0.0, 0.0, 0.0 }; for (int i = 0; i < payScaleTable.length; i++) { for (int j = 0; j < payScaleTable[i].length; j++) { average[i] += payScaleTable[i][j]; } average[i] = average[i] / payScaleTable[i].length; ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
28
Java Implementation of 2-D Arrays
Intro to OOP with Java, C. Thomas Wu Java Implementation of 2-D Arrays The sample array creation payScaleTable = new double[4][5]; is really a shorthand for payScaleTable = new double [4][ ]; payScaleTable[0] = new double [5]; payScaleTable[1] = new double [5]; payScaleTable[2] = new double [5]; payScaleTable[3] = new double [5]; The concept of the two-dimensional array in Java is just that: a concept. There is no explicit structure called the “two-dimensional array” in Java. The two-dimensional array concept is implemented by using an array of arrays. ©The McGraw-Hill Companies, Inc.
29
10.5 Two-Dimensional Arrays
Intro to OOP with Java, C. Thomas Wu 10.5 Two-Dimensional Arrays Subarrays may be different lengths. Executing triangularArray = new double[4][ ]; for (int i = 0; i < 4; i++) triangularArray[i] = new double [i + 1]; results in an array that looks like: An array that is part of another array is called a subarray. An array of arrays may be initialized when it is created. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
30
Intro to OOP with Java, C. Thomas Wu
Lists and Maps The java.util standard package contains different types of classes for maintaining a collection of objects. These classes are collectively referred to as the Java Collection Framework (JCF). JCF includes classes that maintain collections of objects as sets, lists, or maps. A Java interface defines only the behavior of objects It includes only public methods with no method bodies. It does not include any data members except public constants No instances of a Java interface can be created ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
31
Intro to OOP with Java, C. Thomas Wu
JCF Lists JCF includes the List interface that supports methods to maintain a collection of objects as a linear list L = (l0, l1, l2, , lN) We can add to, remove from, and retrieve objects in a given list. A list does not have a set limit to the number of objects we can add to it. A list being linear means the object, or elements, in the list are positioned in a linear sequence. That is, l0 is the first element, l1 is the second element, and so forth. A list has not size limit; there is no set limit to the number of elements we can add to a list. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
32
Intro to OOP with Java, C. Thomas Wu
List Methods Here are five of the 25 list methods: boolean add ( Object o ) Adds an object o to the list void clear ( ) Clears this list, i.e., make the list empty Object get ( int idx ) Returns the element at position idx boolean remove ( int idx ) Removes the element at position idx int size ( ) Returns the number of elements in the list There are total of 25 methods defined in the List interface. The five listed here are the very frequently used subset of those 25 methods. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
33
Intro to OOP with Java, C. Thomas Wu
Using Lists To use a list in a program, we must create an instance of a class that implements the List interface. Two classes that implement the List interface: ArrayList LinkedList The ArrayList class uses an array to manage data. The LinkedList class uses a technique called linked-node representation. Because both the ArrayList and LinkedList classes implement the same interface, we know that instances of ArrayList and LinkedList behave the same way, i.e., they support the same set of public methods defined in the List interface. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
34
Intro to OOP with Java, C. Thomas Wu
Sample List Usage Here's an example of manipulating a list: import java.util.*; List friends; Person person; friends = new ArrayList( ); person = new Person("jane", 10, 'F'); friends.add( person ); person = new Person("jack", 6, 'M'); Person p = (Person) friends.get( 1 ); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
35
Intro to OOP with Java, C. Thomas Wu
JCF Maps JCF includes the Map interface that supports methods to maintain a collection of objects (key, value) pairs called map entries. key value k0 k1 kn v0 v1 vn . one entry We can add to, remove from, and retrieve objects in a given list. A list does not have a set limit to the number of objects we can add to it. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
36
Intro to OOP with Java, C. Thomas Wu
Map Methods Here are five of the 14 list methods: void clear ( ) Clears this list, i.e., make the map empty boolean containsKey ( Object key ) Returns true if the map contains an entry with a given key Object put (Object key, Object value) Adds the given (key, value) entry to the map boolean remove ( Object key ) Removes the entry with the given key from the map int size ( ) Returns the number of elements in the map There are total of 14 methods defined in the List interface. The five listed here are the very frequently used subset of these 14 methods. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.
37
Intro to OOP with Java, C. Thomas Wu
Sample Map Usage Two classes that implement the Map interface: HashMap TreeMap Here's an example of manipulating a map: import java.util.*; Map catalog; catalog = new TreeMap( ); catalog.put("CS101", "Intro Java Programming"); catalog.put("CS301", "Database Design"); catalog.put("CS413", "Software Design for Mobile Devices"); if (catalog.containsKey("CS101")) { System.out.println("We teach Java this semester"); } else { System.out.println("No Java courses this semester"); } The (key, value) pair for this sample map is the course number and the course title, respectively. ©The McGraw-Hill Companies, Inc.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.