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

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

Embed Size (px)

Citation preview

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

Two-Dimensional Arrays

That’s 2-D Arrays Girls & Boys!

One-Dimensional Arrays on Steroids!

Page 2: 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.

• A two dimensional array is really an “array of

arrays” where each element of a one-dimensional

array contains another array.

Page 3: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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];

Page 4: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

Conceptualizing Two-D Arrays

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.

int [ ] [ ] table = new int [4][5];

Page 5: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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.

Page 6: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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.

Page 7: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

Examples of Two-D Array Declarationsint [ ] [ ] 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];

Page 8: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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)

Page 9: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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

Page 10: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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.

Page 11: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

Using table.length & table[row].lengthint [ ] [ ] 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.

Page 12: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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.

Page 13: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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 ];

}

}

Page 14: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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.

Page 15: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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();

Page 16: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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();

Page 17: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

Storing Employees in a 2D ArrayEmployee [ ] [ ] 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);

}

Page 18: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

Row-Sum Example

• 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

5 10 15 20

The code to accomplish this is on the next slide.

Page 19: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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 ];

}

}

Page 20: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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.

Page 21: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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 elementstable[1] = new int[10]; // row 1 has 10 elementstable[2] = new int[100]; // row 2 has 100 elementstable[3] = new int[1]; // row 3 has 1 element

Page 22: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

10.10 The TicTacToe Program UML

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

In the TicTacToe programming project we will divide the responisibility of different parts of the program between three files:

1) The Square class is an all purpose class that can be used with numerous board games.

2) The TicTacToeBoard class manages the functions of a TicTacToe game and implements it as a two-dimensional array of Square objects.

3) The TicTacToeGUI class is a view file that sets up the GUI and instantiates the TicTacToeBoard and processes the moves by the players.

Page 23: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

10.10 Diagram of the TicTacToe Program

“-”

false

“-”

false

“-”

false

“-”

false

“-”

false

“-”

false

“-”

false

“-”

false

“-”

false

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.

Page 24: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

10.10 Diagram of the TicTacToe Program

“X”

true

“O”

true

“X”

true

“-”

false

“X”

true

“O”

true

“X”

true

“O”

true

“O”

true

If the Xs win the state of the board might be this.

Page 25: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

10.10 Diagram of the TicTacToe Program

“X”

true

“O”

true

“X”

true

“X”

true

“X”

true

“O”

true

“O”

true

“X”

true

“O”

true

If the game is a tie then the state of the board might be this.

Page 26: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

The Software Layers of TicTacToe

9 1

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

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.

Square Class

TicTacToeBoard Class

TicTacToeGUI Class

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.

Page 27: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

The Software Layers of TicTacToe

Square model class

TicTacToeBoard model class

TicTacToeGUI driver 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.

Page 28: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

The Square Model Class Methods The Square class has two instance variables the String value and the boolean chosen. 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.

Page 29: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

The TicTacToeBoard Model Class Methods

The TicTacToeBoard class has only one instance variable the two-dimensional array of Square objects named board. 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().

Page 30: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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

Page 31: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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.

Page 32: Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

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.

Square model class

TicTacToeBoard model class

TicTacToeGUI driver class