Users.cs.fiu.edu



-5669280268605Figure 5 Input and output from program00Figure 5 Input and output from programMulti-Dimensional ArraysJava like many other programming languages makes provision for multi-dimensional arrays. The general format for multi-dimensional array is as follows:data_type arr [ ][ ][ ]…..Where data_type represents the kind of data that the array will store; arr, represents the name of the array; and the pairs of square brackets represent the dimension of the array. The most commonly used arrays are one-dimensional, two-dimensional, and three-dimensional. Higher dimensional arrays are less frequently used. Only two-dimensional arrays will be discussed in this section.Two-Dimensional ArraysA two-dimensional array is an array of references. Each of the references points to a linear array of values. For example, Figure 6 is an array of four references; each reference points to a linear array of three values. This construct represents what is called a 4 by 3 array. 165735131445Figure 6 - A 4 x 3 array00Figure 6 - A 4 x 3 arrayExample 6 – Declaring Two-Dimensional ArraysThe format for declaring a two-dimensional array satisfies any of the following three formats:15367076200data_type [][] arr; or data_type [] arr[]; ordata_type arr[][];00data_type [][] arr; or data_type [] arr[]; ordata_type arr[][];Let us create a 4 by 3 array to store integers. To create this 4 by 3 array we first have to declare the array variable, and then create the array. Let us call this array numbers. To declare it we would write:33972584455int number[][]; 00int number[][]; 406844587630number00numberAt this point, only the reference address for the array is allocated:The following statement creates the array:number = new int[4][3];81915324485number000000000000Figure 7 - A 4 x 3 integer array00number000000000000Figure 7 - A 4 x 3 integer arrayThis statement has the effect of creating the array as shown in Figure 7. Because the array is an integer array, the compiler loads each cell with the default value for integer variables; in this case zero.Example 7 - Calculating Averages Consider the following situation. Write a program that:Tabulates the test scores for a set of students.Finds the average score for each student.Finds the average score on each testFinds the class average on all tests, and for all the students.Let us use the data in Figure 8 to illustrate the point.StudentTest 1Test 2Test 31000-180701001000-27580801000-36090801000-4808060-3493135172085Figure 8 - Table of students’ test scores00Figure 8 - Table of students’ test scoresFrom the data given in Figure 6, and the requirements listed above, we will design an array large enough to store the test scores, the average for each student, the average for each test, and the class average. In this case we will use a two-dimensional array of size 5 rows by 4 columns. See Figure 9.28194045720scoresFigure 9 - The 5 x 4 integer array called scoresTest scoresTest averagesStudents’ averagesClass average00scoresFigure 9 - The 5 x 4 integer array called scoresTest scoresTest averagesStudents’ averagesClass averageIn addition to the two-dimensional array, we also need to create a one dimensional array to store the id number of each student. The id numbers will be stored as strings for two reasons – firstly, they usually are not used in calculations, and secondly, they sometimes come with characters other than digits. The last cell in this array will have no student id, but instead it will be used as a label for averages.Listing 6 shows the complete test class that creates the arrays and loads the arrays. Focus will be on the declaration, creation, and manipulation of the two-dimensional array. Line 14 for example, shows how the two-dimensional array is declared and created. That is,39497069850double scores[][] = new double[ROWS][COLUMNS];00double scores[][] = new double[ROWS][COLUMNS];Two-dimensional arrays are almost always processed using nested for loops. The two index variables are often referred to as i and j, though any other name would be as good. The first index, i, refers to the ith row of the array, and the second index, j, refers to the jth column of the array.Once the arrays have been created, it is now time to load them with values. Lines 30 thru 39 show the how both arrays are loaded. The for loop of Lines 30 excludes the last row of the array. This is indicated by the expression, i < scores.length-1. Similarly, the last column is excluded, as indicated by, j < scores[i].length-1. These cells are reserved for the rows and columns averages.652780118110for (int i = 0; i < scores.length-1; i++) {System.out.print("Enter id for student " + (i+1) + "--> ");student[i] = scan.next();for (int j = 0; j < scores[i].length-1; j++) {System.out.print("Enter score " + (j+1) + "---> ");arr[i][j] = scan.nextDouble();}}00for (int i = 0; i < scores.length-1; i++) {System.out.print("Enter id for student " + (i+1) + "--> ");student[i] = scan.next();for (int j = 0; j < scores[i].length-1; j++) {System.out.print("Enter score " + (j+1) + "---> ");arr[i][j] = scan.nextDouble();}} Line 33 shows how the array student stores the id numbers. Line 37 shows how the test scores are stored in the cells of each row. The inner loop controls the reading of the scores for each cell of the rows. Listing 6 shows the complete definition for the class Test2DArray.698500157480import java.util.Scanner;class Test2DArray {public static void main(String[] arg) {Scanner scan = new Scanner(System.in);System.out.print("Enter the number of rows ---> ");final int ROWS = scan.nextInt();System.out.print("Enter the number of columns ---> ");final int COLUMNS = scan.nextInt();String student[] = new String[ROWS];double scores[][] = new double[ROWS][COLUMNS];loadArray(scores, student, scan);StudentScore s = new StudentScore(scores, student);System.out.println("\n.... Original array .....");s.print();s.average_row();System.out.println("\n.... Average row .....");s.print();s.average_column();System.out.println("\n.... Average column .....");s.print();}static void loadArray(double [][]scores, String student[], Scanner scan){for (int i = 0; i < scores.length-1; i++) {System.out.print("Enter id for student " + (i+1) + "--> ");student[i] = scan.next();for (int j = 0; j < scores[i].length-1; j++) {System.out.print("Enter score " + (j+1) + "---> ");arr[i][j] = scan.nextInt();}}student[scores.length-1] = "Avg";}}00import java.util.Scanner;class Test2DArray {public static void main(String[] arg) {Scanner scan = new Scanner(System.in);System.out.print("Enter the number of rows ---> ");final int ROWS = scan.nextInt();System.out.print("Enter the number of columns ---> ");final int COLUMNS = scan.nextInt();String student[] = new String[ROWS];double scores[][] = new double[ROWS][COLUMNS];loadArray(scores, student, scan);StudentScore s = new StudentScore(scores, student);System.out.println("\n.... Original array .....");s.print();s.average_row();System.out.println("\n.... Average row .....");s.print();s.average_column();System.out.println("\n.... Average column .....");s.print();}static void loadArray(double [][]scores, String student[], Scanner scan){for (int i = 0; i < scores.length-1; i++) {System.out.print("Enter id for student " + (i+1) + "--> ");student[i] = scan.next();for (int j = 0; j < scores[i].length-1; j++) {System.out.print("Enter score " + (j+1) + "---> ");arr[i][j] = scan.nextInt();}}student[scores.length-1] = "Avg";}}827405-1905Listing 6 – Creating and loading arrays00Listing 6 – Creating and loading arraysNow that the arrays are loaded, it is time to manipulate them. There are basically three operations that we will perform on the data – display the arrays as a table of values, calculate the students’ average on all three tests (average the rows), and calculate the test averages on all the tests (average the columns). We will implement these operations independently of the test class, by developing a class called StudentScore. Apart from a constructor the class defines three mutator methods – display(), average_row() and average_column(). See Listing 7. 33401016510class StudentScore {double score[][];String student[];StudentScore(double arr[][], String student[]){score = arr;this.student = student;}void display(){System.out.printf("%4s %14s %5s %5s %5s%n", "Id", "Test 1", "Test 2", "Test 3", "Avg");for (int i = 0; i < score.length; i++){System.out.printf("%8s", student[i]);for (int j = 0; j < score[i].length; j++)System.out.printf("%8d", score[i][j]);System.out.printf("%n");}}void average_row(){for (int i = 0; i < score.length; i++){double sum = 0;int length = score[i].length;for (int j = 0; j < length-1; j++)sum = sum + score[i][j]; score[i][length-1] = sum/(length-1);}}void average_column() {int cols = score[0].length;double tavge = 0;for (int j = 0; j < cols-1; j++) {int i = 0; double sum = 0;while (i < score.length){sum = sum + score[i][j];i++;}score[i-1][j] = sum/cols;tavge = tavge + score[i-1][j-1];}score[score.length-1][cols-1] = tavge/(cols-1); }}Listing 7 - Class StudentScore00class StudentScore {double score[][];String student[];StudentScore(double arr[][], String student[]){score = arr;this.student = student;}void display(){System.out.printf("%4s %14s %5s %5s %5s%n", "Id", "Test 1", "Test 2", "Test 3", "Avg");for (int i = 0; i < score.length; i++){System.out.printf("%8s", student[i]);for (int j = 0; j < score[i].length; j++)System.out.printf("%8d", score[i][j]);System.out.printf("%n");}}void average_row(){for (int i = 0; i < score.length; i++){double sum = 0;int length = score[i].length;for (int j = 0; j < length-1; j++)sum = sum + score[i][j]; score[i][length-1] = sum/(length-1);}}void average_column() {int cols = score[0].length;double tavge = 0;for (int j = 0; j < cols-1; j++) {int i = 0; double sum = 0;while (i < score.length){sum = sum + score[i][j];i++;}score[i-1][j] = sum/cols;tavge = tavge + score[i-1][j-1];}score[score.length-1][cols-1] = tavge/(cols-1); }}Listing 7 - Class StudentScoreFirst we look at the method, display, in particular Lines 14 thru 20. In this piece of code the for loop of Line 14 controls the row references of the two-dimensional array, and Line 17 controls the individual cells in the ith row. See the expression j < score[i].length. The scores are extracted from the array, denoted by the expression score[i][j]). Notice also that for each row reference the student’s identification number is displayed, as shown in Line 16. 24320536195for (int i = 0; i < score.length; i++){System.out.printf("%8s", student[i]);for (int j = 0; j < score[i].length; j++)System.out.printf("%8.0f", score[i][j]);System.out.printf("%n");}00for (int i = 0; i < score.length; i++){System.out.printf("%8s", student[i]);for (int j = 0; j < score[i].length; j++)System.out.printf("%8.0f", score[i][j]);System.out.printf("%n");}The method average_row first sums the test scores, one student at a time. See Lines 28 and 29. After each student’s scores are added, the average is taken. This average is then assigned to the last position in that row. See Line 30. Notice that the last position in the ith row always has indices pair (i-1, length-1).18732529210for (int i = 0; i < score.length ; i++){double sum = 0;int length = score[i].length;for (int j = 0; j < length-1; j++)sum = sum + score[i][j]; score[i-1][length-1] = sum/(length-1);}00for (int i = 0; i < score.length ; i++){double sum = 0;int length = score[i].length;for (int j = 0; j < length-1; j++)sum = sum + score[i][j]; score[i-1][length-1] = sum/(length-1);}2921001534795int cols = score[0].length;double tavge = 0;for (int j = 0; j < cols; j++) {int i = 0;double sum = 0;while (i < score.length){sum = sum + score[i][j];i++;}score[i-1][j] = sum/cols;tavge = tavge + score[i-1][j];}score[score.length-1][cols-1] = tavge/cols;00int cols = score[0].length;double tavge = 0;for (int j = 0; j < cols; j++) {int i = 0;double sum = 0;while (i < score.length){sum = sum + score[i][j];i++;}score[i-1][j] = sum/cols;tavge = tavge + score[i-1][j];}score[score.length-1][cols-1] = tavge/cols;The method average_column does two things – first, it finds the average for each test, and it finds the class average for all tests. See Lines 35 thru 49. In this piece of code we start with the column index. See Line 37. Using the row index we now visit every cell in that column, and sum those values. See the while loop, Lines 41 thru 45. The average is calculated when the while loop terminates. This value is then assigned to the last cell of that column. Notice that the indices for the last cell in each column are denoted by the index pair (i-1, j). Within the for loop the individual test averages are being summed in the variable called, tavge. See Line 47. After all test averages have been calculated, the class average is calculated and is assigned to the very last cell in the array. The last cell is denoted by the index pair (score.length-1, cols-1). See Line 49.Figure 10 shows the output from this program, using the data in Figure 8. 23241086995Figure 10 - Output using the data of Figure 6THE CLASS ArrayListOne of the disadvantages of arrays is that after the array is created, its size cannot be changed. It can neither grow nor shrink, which means that you must know in advance how many elements you want to store before creating it. Sometimes this is not always the case; you may not know until run time exactly how large an array you need. For instance, in a classroom situation the teacher will know the exact number of students in a class, so an array would be appropriate. However, in the case of commercial banking, it cannot be ascertained in advance how many people will become customer of the bank, or how many customers might close their accounts with the bank. To handle this latter situation, Java defines a class called ArrayList to handle any unexpected growth or shrinkage of a list. This means that the list adjusts its size dynamically during runtime. ArrayLists are created with an initial size. The default initial capacity of an ArrayList is 10. When this size is exceeded, the list capacity is automatically enlarged. On the other hand, when objects are removed, the array may be shrunken. As with arrays, ArrayList uses index to access the list. The index begins at zero. Unlike arrays, ArrayList can store homogeneous as well as heterogeneous objects. Primitive types are not permitted. Java 1.5 and later versions allow you to restrict the type of object to be stored. Figure 11 shows the constructors and some frequently used methods of the ArrayList class. ConstructorsPurposeArrayList( )Builds an empty array list.ArrayList(Collection c)Builds an array list that is initialized with the elements of the collection cArrayList(int capacity)Builds an array list that has the specified initial capacity.Frequently used methodsPurposeboolean add(E e)Appends the specified element to the listvoid clear()Removes all of the elements from this list.E get(int index)Returns the element at the specified position in this list.boolean isEmpty()Returns true if this list contains no elementsE remove( int index)Removes the element at the specified position in this list.boolean remove(Object o)Removes the first occurrence of the specified element from this list, if it is present.E set(int?index, E?element)Replaces the element at the specified position in this list with the specified element.int size()Returns the number of elements in this list.762003650615Figure 11 - Constructors and some frequently used methods00Figure 11 - Constructors and some frequently used methodsExample 7 - Some ArrayList Operations The following example serves to demonstrate using some of the methods in the class ArrayList. This example demonstrates how to append, insert, replace, and remove objects from the list. It also shows that the data to be stored are all objects, including user-defined classes. See Listing 8 shows a user-defined class called Person. This class will be used in this example.11938064770class Person{private String name;private int age;Person(String name, int age){this.name = name;this.age = age;}public String toString() { return name + " age " + age ; }}Listing 8 - User defined class Person00class Person{private String name;private int age;Person(String name, int age){this.name = name;this.age = age;}public String toString() { return name + " age " + age ; }}Listing 8 - User defined class PersonListing 9 shows a class called CheckArrayList. It creates an ArrayList object that can store just about any type of object. This is denoted by the type shown within the pairs of angle brackets. See Line 7.67310118110import java.util.ArrayList;class CheckArrayList{public static void main(String[] arg){ArrayList <Object> list = new ArrayList<Object>();list.add("World");display(list);list.add(0, "Hello");display(list);list.add(1, 'C'); display(list);list.add(new Character('P'));display(list);System.out.println("\nRemove the object " + list.remove(3));display(list);list.add(new Integer(25));display(list);list.add(100.0);display(list);list.add(3, new Person("Boris Gardener", 69));display(list);list.set(0, new Person("Bill Henry", 26));display(list);}static void display(ArrayList list){System.out.println("\nThe size of the list is " + list.size());for (int i = 0; i < list.size(); i++){Object o = list.get(i);if ( o instanceof String )System.out.println("Object position " + i + " " + (String)o + " is a string " );else if (o instanceof Integer)System.out.println("Object position " + i + " " + (Integer)o + " is an integer " );else if (o instanceof Double)System.out.println("Object position " + i + " " + (Double)o + " is a double " );else if (o instanceof Character)System.out.println("Object position " + i + " " + (Character)o + " is an character " );else if (o instanceof Person)System.out.println("Object position " + i + " " + (Person)o + " is a person " );}}}Listing 9 - The class CheckArrayList00import java.util.ArrayList;class CheckArrayList{public static void main(String[] arg){ArrayList <Object> list = new ArrayList<Object>();list.add("World");display(list);list.add(0, "Hello");display(list);list.add(1, 'C'); display(list);list.add(new Character('P'));display(list);System.out.println("\nRemove the object " + list.remove(3));display(list);list.add(new Integer(25));display(list);list.add(100.0);display(list);list.add(3, new Person("Boris Gardener", 69));display(list);list.set(0, new Person("Bill Henry", 26));display(list);}static void display(ArrayList list){System.out.println("\nThe size of the list is " + list.size());for (int i = 0; i < list.size(); i++){Object o = list.get(i);if ( o instanceof String )System.out.println("Object position " + i + " " + (String)o + " is a string " );else if (o instanceof Integer)System.out.println("Object position " + i + " " + (Integer)o + " is an integer " );else if (o instanceof Double)System.out.println("Object position " + i + " " + (Double)o + " is a double " );else if (o instanceof Character)System.out.println("Object position " + i + " " + (Character)o + " is an character " );else if (o instanceof Person)System.out.println("Object position " + i + " " + (Person)o + " is a person " );}}}Listing 9 - The class CheckArrayListFigure 12 shows the output generated from the program. In Listing 10, Line 9 places the first object in the list. When the list is displayed (Line 10) its size is 1, and the string object World is stored in the first position, 0. Line 11 has the effect of inserting this new object at the first location, thereby repositioning the first object to the second position, 1. When the list is displayed you will notice that there are two elements in the list, and that they are in their respective position as described. Line 13 has the similar effect as Line 11, except that the data being stored appears to be a primitive type. Yes, the character ‘C’ is a primitive type; however, it is converted internally to an object of type Character before it is placed in the list. This construct works for Java 1.5 and later versions.128905108585-4487545111125First object to be added to the listSecond object displaces the firstThird object to be inserted in the list displaces the secondThe fourth object is removed from the listList is down from 4 to 3 elementsA fourth object is appended to the listA fifth object to be appended to the listThis object replaces the firstThe fourth object to be appended to the listFigure 12 - The output from the program am00First object to be added to the listSecond object displaces the firstThird object to be inserted in the list displaces the secondThe fourth object is removed from the listList is down from 4 to 3 elementsA fourth object is appended to the listA fifth object to be appended to the listThis object replaces the firstThe fourth object to be appended to the listFigure 12 - The output from the program am40557455003165This fourth object displaces third and fourth objects00This fourth object displaces third and fourth objectsLine 15 appends the character object ‘P’ to the list. This addition increases the size of the list by 1, to 4. Line 17 removes the fourth element from the list, which happens to be the last element added. The list size is reduced to 3. Line 19 has similar effect as Line 15; and Line 21 has similar effect as Line 13, except that in this case the object is appended to the list. With these two additions, the list now has 5 elements. As was stated, ArrayList can store heterogeneous objects. In Line 23 the object of the user defined class Person is created and is inserted in the fourth position in the list. Hence it displaces the objects that were occupying the third and fourth position in the list. At this point the list has 6 elements. In Line 25 the new Person object replaces the object in the first position in the list. The replaced object is completely gone. Notice that the size of the list is still 6. When a list has different types of object we mustJava provides the instanceof operator which enables us to identify objects according to their type. See the if/else statement, Lines 34 thru 42 ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download