1 / 32

Two-Dimensional Arrays

Two-Dimensional Arrays. That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!. Two-D Arrays Are Tables. Arrays may have multiple dimensions . Two-dimensional arrays can be visualized as tables with rows and columns .

Télécharger la présentation

Two-Dimensional Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

  2. Two-D Arrays Are Tables • Arrays may have multiple dimensions. • Two-dimensional arrays can be visualized as tables with rows and columns. • A two dimensional array is really an“array of arrays” where each element of a one-dimensional array contains another array.

  3. Declaring & Instantiating Two-D Arrays A good name for a two-dimensional array variable is table . Here is how you would declare and instantiate a two-dimensional array of integers with 4 rows and 5 columns: int [ ] [ ] table = new int [4] [5];

  4. Conceptualizing Two-D Arrays int [ ] [ ] table = new int [4][5]; The variable table references an array of four elements. Each of these elements in turn references an array of five integers … table is really an array of arrays.

  5. Conceptualizing Two-D Arrays More specifically, table is an array of four memory locations and in each memory location of that array there is an array that has five memory locations. So table[0] refers to the first row of the 2D array and table[1] refers to the second row, table[2] refers to the third row and table[3] refers to the fourth row. Using the code table[2][3] allows us to work with the memory location in the third row and fourth column named row 2 column 3.

  6. Conceptualizing Two-D Arrays A table of numbers, for instance, can be implemented as a two-dimensional array. The figure shows a two-dimensional array with four rows and five columns that contains some numbers.

  7. Examples of Two-D Array Declarations int [ ] [ ] nums = new int [4][5]; double[ ] [ ] averages = new double [4][5]; String [ ] [ ] names = new String [4][5]; Student [ ] [ ] seatingChart = new Student [4][5]; Employee [ ] [ ] employees = new Employee [4][5];

  8. Accessing an Element of a Two-D Array Suppose we name the array table; then to indicate an element in table, we specify its row and column position, remembering that index values start at 0: x = table[2][3]; // Set x to 23, the value in (row 2, column 3)

  9. Storing Values in a Two-D Array • Here is the declaration & construction for a new table: • int [ ] [ ] table = new int [3][4]; • Let’s say we want these values stored in the array: • 0 1 2 3 • 1 2 3 4 • 3 4 5 Then the code that will do that is ….

  10. Storing Int Values in a Two-D Array int [ ] [ ] table = new int [3][4]; The code to store these values could be: for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) { table[ row] [ col] = row + col; } } row and col are much better names for the loop control variables as they add readability to the code … helping us remember which loop controls the row we are on and which controls which column we are on.

  11. Using table.length & table[row].length • int [ ] [ ] table = new int [3][4]; • Since the array might be resized later, then the code to store these values should be: • for (int row = 0; row < table.length; row++) • for (int col = 0; col < table[row].length; col++) • table[ row ] [ col ] = row + col; • table.length is the number of rows • table[ row ].length is the number of columns • Since we only have one line of code in the inner loop we do away with curly braces for that loop and we don’t have them for the outer loop because a loop is considered to be one statement.

  12. Printing the values of a Two-D Array for (int row = 0; row < table.length; row ++) { for (int col = 0; col < table[row].length; col ++) { System.out.print(table[ row ] [ col ] + “ ”); } System.out.println();// outside inner loop } Just like in the NestedLoopMania program, the System.out.println statement outside the inner loop starts a new row of output.

  13. Summing Elements of a Two-D Arrays If we wanted to sum the values in the array, we could use: int sum = 0; for (int row = 0; row < table.length; row++) { for (int col = 0; col < table[ row ].length; col++) { sum += table[ row ] [ col ]; } }

  14. Alternate Declarations and Construction • Just like one-dimensional arrays, two-dimensional arrays may be declared and instantiating in two different lines: // The following line of code can be broken down into: int [][] table = new int [4][5]; int [ ][ ] table; // Declaring a 2D array reference variable table = new int [4][5]; // Instantiating a 2D array for table It makes more sense to do it all in one line.

  15. Storing Doubles in a 2D Array • double [ ] [ ] table = new double [7][6]; • The following code stores random floating point values between 0 inclusive and 1.0 exlcusive in the 2D array: • for (int row = 0; row < table.length; row++) • for (int col = 0; col < table[row].length; col++) • table[ row ] [ col ] = Math.random();

  16. Storing Strings in a 2D Array • String [ ] [ ] table = new String [10][10]; • Scanner reader = new Scanner (System.in); • The following code stores string values from the keyboard into the 2D array: • for (int row = 0; row < table.length; row++) • for (int col = 0; col < table[row].length; col++) • table[ row ] [ col ] = reader.nextLine();

  17. Storing Employees in a 2D Array Employee [ ] [ ] table = new Employee [5][10]; Scanner reader = new Scanner (System.in); The following code stores Employee values from the keyboard into the 2D array: for (int row = 0; row < table.length; row++) for (int col = 0; col < table[row].length; col++) { System.out.print(“Enter the employee name: ”); String name = reader.nextLine(); System.out.print(“Enter the employee gender: ”); String gender = reader.nextLine(); table[ row ] [ col ] = new Employee (name, gender); }

  18. Row-Sum Example 5 10 15 20 • We can compute the sum of each row separately and place each sum in a one-dimensional array named rowSum. Here is how we can visualize our data structures: • A one dimensional array called rowSum to store the sum of each row in table. • A two-dimensional array called table to hold all the values for the program. 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 The code to accomplish this is on the next slide.

  19. Row-Sum Example Code • The code for calculating the sum of each row and storing it in the array rowSum. The size of rowSum should be the number of rows in the 2D array table. int [ ] rowSum = new int [table.length]; for (int row = 0; row < table.length; row++) { for (int col = 0; col < table[ row ].length; col++) { rowSum[ row ] += table[ row ] [ col ]; } }

  20. Two-D Array Initializer Lists • Declaring and instantiating a two-dimensional array of integers using an initializer list: int[][] table = {{ 0, 1, 2, 3, 4} , // row 0 {10, 11, 12, 13, 14} , // row 1 {20, 21, 22, 23, 24} , // row 2 {30, 31, 32, 33, 34} // row 3 }; Notice there is no comma after the last row. The number of inner lists determines the number of rows.So the number of values in each list determines the number of columns.

  21. Ragged Arrays • Ragged arrays are rows of a two-dimensional array that are not all the same length. We mention them in passing. You do not need to know them for the AP Exam. int[ ][ ] table; table = new int[4][ ]; // table has 4 rows // no columns specified table[0] = new int[6]; // row 0 has 6 elements table[1] = new int[10]; // row 1 has 10 elements table[2] = new int[100]; // row 2 has 100 elements table[3] = new int[1]; // row 3 has 1 element

  22. Square class defines a Square object TicTacToeBoard class defines and manages a TicTacToeBoard TicTacToeGUI class an applet driver program that displays and manges the TicTacToe Game 9 1 10.10 The TicTacToe Program UML In the TicTacToe programming project we will divide the responisibility of different parts of the program between three files: The Square class is an all purpose class that can be used with numerous board games. The TicTacToeBoard class manages the functions of a TicTacToe game and implements it as a two-dimensional array of Square objects. The TicTacToeGUI class is a view file that sets up the GUI and instantiates the TicTacToeBoard and processes the moves by the players.

  23. 10.10 Diagram of the TicTacToe Program Each memory location of the two-dimensional array contains a Square object that has two instance values …. a String which is initially set to “-” and a boolean which is set to “false”. When a player chooses a location on the board, then the String value is changed to either an “X” or “O” and the boolean value is changed to “true” to indicate the location has been chosen.

  24. 10.10 Diagram of the TicTacToe Program If the Xs win the state of the board might be this.

  25. 10.10 Diagram of the TicTacToe Program If the game is a tie then the state of the board might be this.

  26. The Software Layers of TicTacToe TicTacToeBoard Class The TicTacToeBoard class constructs and mangaes a two-dimensional array of Square objects. The methods of this class are called by the driver class TicTacToeGUI. However, the methods in this class call methods of the Square class to do their work. Square Class TicTacToeGUI Class The Square class makes changes to Square objects and returns values when needed to the TicTacToeBoard class where the Square class methods are called. The TicTacToeGUI driver class manages the view and interactions of the program with the user and controls the game by calling methods of the TicTacToeBoard class based on the input received from the GUI. 9 1 This is an example of software layering, where different files have different responsibilities but each class only has access to the class immediately below it.

  27. The Software Layers of TicTacToe TicTacToeGUI driver class TicTacToeBoard model class Square model class In software layering, you usually only want a class to have access to the methods in the class below it. In large software systems, this is desirable and adds an efficient level of organization that allows for testing and troubleshooting.

  28. The Square Model Class Methods • The Square class has two instance variables the Stringvalue and the booleanchosen. The methods that will be called the most are: • the Square(String v, boolean b) initializing constructor • the getValue() accessor method • the getChosen() accessor method • the setValue(String v) mutator method • the setChosen(boolean b) mutator method • These methods will all be called only by the TicTacToeBoard class methods in our TicTacToe program. • The TicTacToeBoard class is the software layer immediately above the Square class.

  29. The TicTacToeBoard Model Class Methods • The TicTacToeBoard class has only one instance variable the two-dimensional array of Square objects namedboard. The most important methods that will be called are: • the TicTacToeBoard () default constructor that constructs the board and fills it with Square objects having values of “-” and false. • the String getBoardSquareValue(int row, int col) accessor method that gets the String value stored in a Square object located at position (row, col) and returns the String value. It gets the String value by calling the Square class accessor method getValue(). • the boolean getBoardSquareChosen(int row, int col)accessor method that gets the boolean value stored in a Square object located at position (row, col) and returns the boolean value. It gets the boolean value by calling the Square class accessor method getChosen().

  30. The TicTacToeBoard Model Class Methods • the boolean setBoardSquareValue(int row, int col, String letter) mutator method that checks the board’s Square chosen boolean value at (row, col) to see if that Square has been chosen yet. If it has not then the method changes the Square’s String value from “-” to “X” or “O”, and its boolean chosen value from false to true. If the method changes the Square’s values then it returns true.If it doesn’t the method returns false. If it changes the Square’s values, it does so by calling the Square class mutator methods setValue() and setChosen(). • the isFull()method checks to see if all of the “-” String values have been changed to “X” or “O”. This method will use a nested loop to check every Square object. If it finds even one “-” value anywhere in the two-dimensional array, then it returns false. If none are found, then it returns true. It does so by calling the Square class accessor method getValue().

  31. The TicTacToeBoard Model Class Methods • the void reset() method resets all the Square objects in the two-dimensional array to “-” and false. It does so by calling the Square class mutator methods setValue() and setChosen(). • the boolean won(String letter)method checks to see if there are three “X”s or three “O”s in any row, column, or diagonal. This method takes the String value passed to it and immediately concatentates three of the letters together to make either “XXX” or “OOO”. It then retrieves all of the String values from the Square objects in a row, column, or diagonal to see if there is a matching three letters. If there is, the “X”s or “O”s have won and the method returns true. If there is no match the method returns false. It does so by calling the Square class accessor method getValue() for every board Square.

  32. The TicTacToeBoard Model Class Methods These methods will all be called only by the TicTacToeGUI driver class methods in our TicTacToe program. The TicTacToeGUI driver class is the software layer immediately above the TicTacToeBoard class. TicTacToeGUI driver class TicTacToeBoard model class Square model class

More Related