16
MULTI-DIMENSIONAL ARRAYS Java 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 ARRAYS A 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. EXAMPLE 6 – DECLARING TWO-DIMENSIONAL ARRAYS The format for declaring a two-dimensional array satisfies any of the following three formats: 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 Figure 6 - A 4 x 3 array data_type [][] arr; or data_type [] arr[]; or data_type arr[][];

users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

  • Upload
    vantruc

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

Page 1: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

MULTI-DIMENSIONAL ARRAYS

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

EXAMPLE 6 – DECLARING TWO-DIMENSIONAL ARRAYS

The format for declaring a two-dimensional array satisfies any of the following three formats:

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:

At this point, only the reference address for the array is allocated:The following statement creates the array:

number = new int[4][3];

Figure 6 - A 4 x 3 array

number

data_type arr[][];

data_type [] arr[]; or

data_type [][] arr; or

int number[][];

Page 2: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

This 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:

1. Tabulates the test scores for a set of students.2. Finds the average score for each student.3. Finds the average score on each test4. Finds the class average on all tests, and for all the students.

Let us use the data in Figure 8 to illustrate the point.

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

Class average

Students’ averages

Test averages

Test scores

Figure 9 - The 5 x 4 integer array called scores

scores

Figure 7 - A 4 x 3 integer array

000

000

0

000

00

number

Student Test 1 Test 2 Test 3

1000-180

70

100

1000-275

80 80

1000-360

90 80

1000-480

80 60

Page 3: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

In 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,

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.

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.

14. double scores[][] = new double[ROWS][COLUMNS];

30.for (int i = 0; i < scores.length-1; i++) 31. {32. System.out.print("Enter id for student " +

(i+1) + "--> ");33. student[i] = scan.next();34. for (int j = 0; j < scores[i].length-1; j++) 35. {36. System.out.print("Enter score " + (j+1) +

"---> ");37. arr[i][j] = scan.nextDouble();

Page 4: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

Now 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

1. import java.util.Scanner;2.3. class Test2DArray {4. public static void main(String[] arg) {5. Scanner scan = new Scanner(System.in);6. System.out.print("Enter the number of rows ---> ");7. final int ROWS = scan.nextInt();8. System.out.print("Enter the number of columns --->

");9. final int COLUMNS = scan.nextInt();10.11. String student[] = new String[ROWS];12. double scores[][] = new double[ROWS]

[COLUMNS];13.14. loadArray(scores, student, scan);15. StudentScore s = new StudentScore(scores,

student);16.17. System.out.println("\n.... Original array .....");18. s.print();19. s.average_row();20. System.out.println("\n.... Average row .....");21. s.print();22. s.average_column();23. System.out.println("\n.... Average column .....");24. s.print();25. }26. static void loadArray(double [][]scores, String student[],

Scanner scan)27. {28. for (int i = 0; i < scores.length-1; i++) 29. {30. System.out.print("Enter id for student " + (i+1)

+ "--> ");31. student[i] = scan.next();32. for (int j = 0; j < scores[i].length-1; j++) 33. {34. System.out.print("Enter score " + (j+1) +

Listing 6 – Creating and loading arrays

Page 5: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

the class defines three mutator methods – display(), average_row() and average_column(). See Listing 7.

Listing 7 - Class StudentScore

1. class StudentScore 2. {3. double score[][];4. String student[];5.6. StudentScore(double arr[][], String student[])7. {8. score = arr;9. this.student = student;10. }11. void display()12. {13. System.out.printf("%4s %14s %5s %5s %5s%n", "Id", "Test 1", "Test

2", "Test 3", "Avg");14. for (int i = 0; i < score.length; i++)15. {16. System.out.printf("%8s", student[i]);17. for (int j = 0; j < score[i].length; j++)18. System.out.printf("%8d", score[i][j]);19. System.out.printf("%n");20. }21. }22. void average_row()23. {24. for (int i = 0; i < score.length; i++)25. {26. double sum = 0;27. int length = score[i].length;28. for (int j = 0; j < length-1; j++)29. sum = sum + score[i][j]; 30. score[i][length-1] = sum/(length-1);31. }32. }33. void average_column() 34. {35. int cols = score[0].length;36. double tavge = 0;37. for (int j = 0; j < cols-1; j++) 38. {39. int i = 0; 40. double sum = 0;41. while (i < score.length)42. {43. sum = sum + score[i][j];44. i++;45. }46. score[i-1][j] = sum/cols;47. tavge = tavge + score[i-1][j-1];48. }49. score[score.length-1][cols-1] = tavge/(cols-1);

Page 6: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

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

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

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

14.for (int i = 0; i < score.length; i++)15. {16. System.out.printf("%8s",

student[i]);17. for (int j = 0; j < score[i].length;

j++)18. System.out.printf("%8.0f",

score[i][j]);

24. for (int i = 0; i < score.length ; i++)25. {26. double sum = 0;27. int length = score[i].length;28. for (int j = 0; j < length-1; j++)29. sum = sum + score[i][j]; 30. score[i-1][length-1] =

sum/(length-1);31. }

35. int cols = score[0].length;36. double tavge = 0;37.for (int j = 0; j < cols; j++) 38. {39. int i = 0;40. double sum = 0;41. while (i < score.length)42. {43. sum = sum + score[i][j];44. i++;

Page 7: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

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.

35. int cols = score[0].length;36. double tavge = 0;37.for (int j = 0; j < cols; j++) 38. {39. int i = 0;40. double sum = 0;41. while (i < score.length)42. {43. sum = sum + score[i][j];44. i++;

Page 8: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

Figure 10 - Output using the data of Figure 6

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

Constructors PurposeArrayList( ) Builds an empty array list.

ArrayList(Collection c)Builds an array list that is initialized with the elements of the collection c

ArrayList(int capacity) Builds an array list that has the specified initial capacity.Frequently used methods Purposeboolean 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 Removes the first occurrence of the specified element

Page 9: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

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

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

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

Figure 11 - Constructors and some frequently used methods

Listing 8 - User defined class Person

1. class Person2. {3. private String name;4. private int age;5.6. Person(String name, int age)7. {8. this.name = name;9. this.age = age;10. }11.12. public String toString() { return name + " age

" + age ; }13. }

Page 10: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

Figure 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

Listing 9 - The class CheckArrayList

1. import java.util.ArrayList;2.3. class CheckArrayList4. {5. public static void main(String[] arg)6. {7. ArrayList <Object> list = new ArrayList<Object>();8.9. list.add("World");10. display(list);11. list.add(0, "Hello");12. display(list);13. list.add(1, 'C'); 14. display(list);15. list.add(new Character('P'));16. display(list);17. System.out.println("\nRemove the object " + list.remove(3));18. display(list);19. list.add(new Integer(25));20. display(list);21. list.add(100.0);22. display(list);23. list.add(3, new Person("Boris Gardener", 69));24. display(list);25. list.set(0, new Person("Bill Henry", 26));26. display(list);27. }28. static void display(ArrayList list)29. {30. System.out.println("\nThe size of the list is " + list.size());31. for (int i = 0; i < list.size(); i++)32. {33. Object o = list.get(i);34. if ( o instanceof String )35. System.out.println("Object position " + i + " " + (String)o + " is a

string " );36. else if (o instanceof Integer)37. System.out.println("Object position " + i + " " + (Integer)o + " is

an integer " );38. else if (o instanceof Double)39. System.out.println("Object position " + i + " " + (Double)o + " is a

double " );40. else if (o instanceof Character)41. System.out.println("Object position " + i + " " + (Character)o + "

is an character " );

Page 11: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

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.

This fourth object displaces third and

Figure 12 - The output from the program am

The fourth object to be appended to the list

This object replaces the first

A fifth object to be appended to the list

A fourth object is appended to the list

List is down from 4 to 3

The fourth object is removed from

Third object to be inserted in the list displaces the second

Second object displaces the first

First object to be added to the

Page 12: users.cs.fiu.edu  · Web viewFigure 5 Input and output from program Multi-Dimensional Arrays. Java like many other programming languages makes provision for multi-dimensional arrays

Line 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 must

Java provides the instanceof operator which enables us to identify objects according to their type. See the if/else statement, Lines 34 thru 42