1 / 60

Chapter 11 The Two-Dimensional Array Data Structure

Chapter 11 The Two-Dimensional Array Data Structure. Section 1 - What is a Two-Dimensional Array? Section 2 - Declaring and Instantiating a 2D Arrays Section 3 - Accessing, Storing, & Printing 2D Arrays Section 4 - Initializer Lists & Enhanced For Loops

lyle-walker
Download Presentation

Chapter 11 The Two-Dimensional Array Data Structure

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. Chapter 11The Two-Dimensional ArrayData Structure Section 1 - What is a Two-Dimensional Array? Section 2 - Declaring and Instantiating a 2D Arrays Section 3 - Accessing, Storing, & Printing 2D Arrays Section 4 - Initializer Lists & Enhanced For Loops Section 5 - The Square Class and PennyPitch Section 6 - The TicTacToe Game Software Layers Go Go Go Go Go Go 1

  2. Chapter 11 Section 1What is aTwo-Dimensional Array? 2

  3. 11.1 2D Arrays Are Tables • A Two-dimensional array can be visualized as a tablewith rows and columns. • A two dimensional array is really an“array of arrays” where each element of a one-dimensional arraycontains another array. • Two-dimensional arrays are used in programs for everythingfrom spreadsheets to board games. You will write the code in this chapter for a number of programs and two games … PennyPitch and Tic-Tac-Toe. 3

  4. 11.1 Visualizing 2D 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 integers that are multiples of 5. Just like one-dimensional arrays where the first element is identified as index 0, row and column indices begin with 0. 4

  5. 11.1 An Array of Arrays The variable table references an array of four elements. Each of these elements in turn references an array of five integers … so table is really anarray of arrays. More specifically, table is an array of four memory locations and in each memory location of that array there is a reference to 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. 5

  6. Chapter 11 Section 2Declaring and Instantiatinga Two-Dimensional Array 6

  7. 11.2 Declaring & Instantiating 2D Arrays A good name for a two-dimensional array variable is table. Here is how you to declare and instantiate a two-dimensional array of integers with 4 rows and 5 columns. Notice the use of two subscript operators [ ] [ ] . int [ ] [ ] table = new int [4] [5]; 7

  8. 11.2 Alternate Declaration and Construction Just like one-dimensional arrays, two-dimensional arrays may be declared and instantiated 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 when possible. 8

  9. 11.2 Examples of 2D Array Declarations int [ ] [ ] nums = new int [25][25]; double[ ] [ ] averages = new double [10][10]; String [ ] [ ] names = new String [5][5]; Student [ ] [ ] students = new Student [4][80]; Employee [ ] [ ] employees = new Employee [8][25]; 9

  10. 11.2 Ragged Arrays • Ragged arrays are a 2D array that has rows that are not all the same length. We mention them in passing. You do not need to know them for the AP Exam. Here is a sample declaration for a ragged array. 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 10

  11. Chapter 11 Section 3Accessing, Storing, and Printing Values in a Two-Dimensional Array 11

  12. 11.3 Accessing Elements of a 2D Array If the 2D array’s name is table; then to indicate an element in table, we specify its row first and then its column position, remembering that index values start at 0: Using table[2][3] allows us to access the value in the third row and fourth column. int x = table[2][3] ; // this stores 70 in x 12

  13. 11.3 Accessing Values in a 2D Array Just like table[2][3] allows us to access the memory location in the third row and fourth column, table[0][4] allows us to access the last memory location in the first row. table[0][4] 13

  14. 11.3 Storing Values in a 2D Array We can store the integer 100 in the array memory location represented by the first rowand first column using … table [0] [0] = 100; The first subscript operator always designates the rowand the second one always designates the column. table [1] [2] = 75; // store 75 in the second row and third column 14

  15. 11.3 Storing Values in a Two-D Array Here again we declare and instantiate table: int [ ] [ ] table = new int [3][4]; Let’s say we want these values stored in the array in this way: Guess how many loops we need to store values in an array? 15

  16. 11.3 Storing Values in a Two-D Array Here again we declare and instantiate table: int [ ] [ ] table = new int [3][4]; Let’s say we want these values stored in the array in this way: Guess how many loops we need to store values in an array? TWO The next slide contains the code that will do that is …. 16

  17. 11.3 Storing Int Values in a 2D Array int [ ] [ ] table = new int [3][4]; The code to store these valuescould 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 one controls the column we are on. 17

  18. 11.3 Storing Int Values in a 2D Array int [ ] [ ] table = new int [3][4]; The code to store these valuescould be: for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) { table[ row] [ col] = row + col; } } Notice the outside loop controls what row you are on and the inside loop controls what column you are on! 18

  19. 11.3 Storing Int Values in a 2D Array int [ ] [ ] table = new int [3][4]; The code to store these valuescould be: for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) { table[ row] [ col] = row + col; } } If you have 3 rows, then you want the outside loop to run 3 times.If you have 4 columns, then you want the inside loop to run 4 times. 19

  20. 11.3 Using table.length & table[row].length • int [ ] [ ] table = new int [3][4]; • Since the code that constructs the array above may be changed later, then the code to store these values should not have numbers as the upper limits of the loops but rather the following: • 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. 20

  21. 11.3 Storing Random Values To store random values between 100 and 200 inclusive in the table we could use: for (int row = 0; row < table.length; row++) for (int col = 0; col < table[row].length; col++) table[ row ] [ col ] = (int)(Math.random() *101) + 100; Just remember that you will always want to write the codeso that it will work with any size 2D array!!! Don’t place actual numbers as the upper limits of the loops!!! 21

  22. 11.3 Storing Values from the Keyboard To store keyboard values in table we could use: for (int row = 0; row < table.length; row++) for (int col = 0; col < table[row].length; col++) { System.out.print(“Enter an integer: ”); table[ row ] [ col ] = reader.nextInt(); } 22

  23. 11.3 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.printf(“%8d” , table[ row ] [ col ]); } System.out.println();// outside inner loop } In the Ch. 6 NestedForLoopMania program, we used nested for loops to print data to the screen and a System.out.println statement outside the inner loop to start a new row of output. We do this here also so that the data can be printed in the form of a table. 23

  24. 11.3 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 exclusive 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(); 24

  25. 11.3 Storing Strings in a 2D Array String [ ] [ ] seatingChart = 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 < seatingChart.length; row++) for (int col = 0; col < seatingChart[row].length; col++) { System.out.print(“Enter the student’s name: ”); seatingChart[ row ] [ col ] = reader.nextLine(); } 25

  26. 11.3 Storing Employees in a 2D Array Employee [ ] [ ] table = new Employee [5][10]; Scanner reader = new Scanner (System.in); The following code stores Employee values 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’s name: ”); String name = reader.nextLine(); System.out.print(“Enter the employee’s gender: ”); String gender = reader.nextLine(); System.out.print(“Enter the employee’s department: ”); String dept = reader.nextLine(); System.out.print(“Enter the employee’s pay rate: ”); double payRate = reader.nextDouble(); table[ row ] [ col ] = new Employee (name, gender, payRate, dept); } 26

  27. 11.3 Example of Summing Each Row 5 10 15 20 • We can compute the sum of each row separately and place each sum in a second one-dimensional array named rowSum. Here is how we can visualize our data structures: • A one dimensional array called rowSum stores the sum of each row in table. • A two-dimensional array called table holds 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. 27

  28. 11.3 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. Assume table has already been filled with values. 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 ]; } } 28

  29. 11.3 A Method that Sums the Multiples of 5 • Look at the code required to sum only the multiples of 5 in a two-dimensional array of int values of any size and return the sum: public static int sumMultsOfFive ( int [ ] [ ] nums) { int sum = 0; for (int row = 0; row < nums.length; row++) { for (int col = 0; col < nums[ row ].length; col++) if (nums[row][col] % 5 == 0) sum += nums [ row ] [ col ]; } return sum ; } 29

  30. 11.3 A Method that returns a 2D Array // user enters the number of rows and cols from keyboard in main // and stores them in the variables rows and cols double [ ] [ ] table = storeDoublesIn2DArray (int rows, int cols); public static double [ ] [ ] storeDoublesIn2DArray (int rows, int cols) { double [ ] [ ] nums= new double [rows][cols]; // construct new array for (int row = 0; row < nums.length; row++) for (int col = 0; col < nums [row].length; col++) nums [ row ] [ col ] = Math.random(); return nums; } Notice how to return a 2D array of double 30

  31. 11.3 Building a 2D Array from a 1D Array // main method code String [ ] wordList = new String [100]; // Assume code that randomly reads 100 words from a large // list of puzzle words and uses a loop to place them in wordList. // The one-dimensional array wordList is now full. // call the method makePuzzleGrid and pass it wordList so that a // two-dimensional array of words will be returned for a game. String [ ] [ ] puzzleGrid =makePuzzleGrid (wordList); 31

  32. 11.3 Building a 2D Array from a 1D Array public static String [ ] [ ] makePuzzleGrid (String [ ] wordList) { int i = 0; String [ ] [ ] puzzleGrid = new String [10] [10]; for (int row = 0; row < puzzleGrid.length; row++) for (int col = 0; col < puzzleGrid[row].length; col++) { puzzleGrid[ row ] [ col ] = wordList [ i ]; i++; } return puzzleGrid; } 32

  33. Chapter 11 Section 4Using Initializer Listsand Enhanced For Loopswith Two-Dimensional Arrays 33

  34. 11.4 2D 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. 34

  35. 11.4 Enhanced For Loops witha 2D Array Here is an example of how to use nested enhanced for loops with a two-dimensional array of integers to print the values in rows and columns for the array. Assume we want to print table. int [ ] [ ] table = { {2, 3, 4} ,{3, 4, 5} , {4, 5, 6} }; for (int [ ] row : table) { for (intelement : row ) { System.out.printf(“%5d”, element); } System.out.println(); } Note that row is a good name for the outside loop variable and it represents a row of the 2D array, which itself is a one-dimensional array. 35

  36. 11.4 Enhanced For Loops witha 2D Array Here is an example of how to use nested enhanced for loops with a two-dimensional array of doubles to sum all of the values in every row and column of table. double [ ] [ ] table = { {2.15, 3.46, 4.83} , {3.72, 4.65, 5.99} , {4.88, 5.32, 6.95} }; double sum = 0.0; for (double [ ] row : table) { for (doubleelement : row ) sum += element ; } System.out.println(“The sum is ” + sum); 36

  37. 11.4 Enhanced For Loops witha 2D Array What if we wanted to print all of the values in table (from the last slide) ON ONE LINE that are less than 4. for (double [ ] row : table) { for (doubleelement : row ) { if ( element < 4 ) System.out.print ( element + “ ”); } } Here we would not add a System.out.println(); statement outside the inner loop. 37

  38. 11.4 Enhanced For Loops witha 2D Array Here is an example of how to use an enhanced for loop with a two-dimensional array of Strings values to concatenate all the string values in table into one string. String [ ][ ] table = { {“A”, “B”, “C”}, {“D”, “E”, “F”} } String str = “”; for (String [ ] row : table) for (String element : row ) str +=element; 38

  39. Chapter 11 Section 5The Square Class and PennyPitch 39

  40. value chosen 11.5 The Square Model Class Many simple board games need to be able to store an object that has a value and an indicator of whether the object has been chosen in locations in the board. A Squareclasscouldmodel the kind of object needed for these kinds of board games. A two-dimensional array of Square objects would work fine for board games like PennyPitch and TicTacToe. You can play these games online. Each Square has two main characteristics represented by two instance variables … value and chosen. True or false would be stored in chosen so that a Square knows whether it has been chosen (picked). Square Object 40

  41. 11.5 The Square Model Class Since the Square class will be used with applet programs that use GUI interfaces, we will make value a String. This will facilitate easy processing of values, since a GUI sees all values as Strings. Value can contain any value we want, a word, letter, or a number. If we wish the value to be an integer, we will store it as a String value, like “3”, because we know we can retrieve it and parse it into an int value. Second, we will make chosen a boolean. Initially, the value of chosen for any Square can be set to either true or false when a Square is constructed, depending on its intended use. In both PennyPitch and TicTacToe, we will initially set chosen for all constructed Square objects to false, because it will indicate that the Square has not been chosen or picked yet. Run the PennyPitch game on line and see how it work, then come back here and continue reading. 41

  42. 11.5 Initial State of a PennyPitch Board Here is how you could visualize the beginning state of a PennyPitch Game with the board containing Square objects with the following values. 42

  43. 11.5 A Board of Square Objects Here is how you could visualize it for the TicTacToe Game, where all Sqaure objects will initially have the value“-” and chosenfalse. 43

  44. 11.5 The Square Model Class Methods • Besides the two Square class instance variables value and chosen. The methods that will be needed 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 be called by the PennyPitch and theTicTacToe programs. 44

  45. 11.5 Calling The Square Constructor Constructing a Square object is just as simple as constructing an Employee or a Student object. Here is how we constructed those objects: Employee emp2 = new Employee ("Steve", "male", 14.75, "sales" ); Employee emp6 = new Employee ("Amber", "female", 16.85, "tech"); Student s1 = new Student(“Bill”, 93, 77, 65); Student s2 = new Student(“Mary”, 90, 85, 72); So how do you construct a Square object? Well the method signature for the initializing constructor is: Square (String v, boolean b) … so …. 45

  46. 11.5 Calling The Square Constructor So how do you construct a Square object? Well … the method signature for the initializing constructor is: Square (String v, boolean b) … so won’t this work … new Square(“1”, false); We can store the Square object in a Square variable like: Square square1 = new Square(“1”, false); or store it directly in a two-dimensional array of Square objects named board if we specify the row and column: board[0][0] = new Square(“1”, false); It is important to note that board[0][0] is or refers to a Square! 46

  47. 11.5 Retrieving the Value of a Square When we want to obtain the value out of a square, then we can call the accessor method to get the value using the Square object represented by board[0][0]. If the value is numeric, then we must parse it to convert the String value to an int. We can do this using: int x = Integer.parseInt(board[0][0].getValue()); If the code is inside a nested for loop structure with loop control variables row and col, then the code inside the loop might be: int x = Integer.parseInt(board[row][col].getValue()); 47

  48. 11.6 The PennyPitch Program UML Square Model class defines a Square object PennyPitch Driver class defines and manages a two-dimensional array of Square Objects 25 In the PennyPitch programming project we will divide the responsibility of different parts of the program between two files: The Square class that defines a Square object and the methods that are used to access them and change them. The Square class is a Model class. The PennyPitch class that is a view file and a driver that sets up the GUI for the game and instantiates 25 Square objects to be stored in a two-dimensional array. This class will set up and control all facets of the game. 48

  49. Chapter 11 Section 6The Tic Tac Toe ProgramSoftware Layers 49

  50. Square class defines a Square object TicTacToeBoard class defines and manages Square objects that are placed in a TicTacToeBoard object TicTacToeGUI class an applet driver program that displays and manages one TicTacToeBoard object and the interactions by the players 9 1 11.6 The TicTacToe Program UML In the TicTacToe programming project we will divide the responsibility of different parts of the program between three files: The Square class that defines a Square object and the methods that are used to manipulate them. The TicTacToeBoard class that manages the details of a TicTacToe game by implementing a TicTacToeBoard as a two-dimensional array of Square objects. The TicTacToeGUI class that is a view file that sets up the GUI and instantiates the TicTacToeBoard and processes the moves by the players. 50

More Related