Anda di halaman 1dari 25

Programming Concepts: 2D arrays

Programming in Java

Copyright Regulations

COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969


WARNING This material has been reproduced and communicated to you by or on behalf of University of South Australia pursuant to Part VB of the Copyright Act 1968 (the Act). The material in this communication may be subject to copyright under the Act. Any further reproduction or communication of this material by you may be the subject of copyright protection under the Act. Do not remove this notice.

Programming in Java

Textbook
Two dimensional arrays Chapter 13, Section 7, pages 544-548

Programming in Java

Lecture Goal
To learn how to use two-dimensional arrays

Programming in Java

Flowchart for Noughts and Crosses


Set up empty grid

False

Neither x or o have won True

True Find empty cell Put x in cell

If turn of x

False Find empty cell Put o in cell

Calculate if the game has finished And swap turns Announce winner
Programming in Java 5

Pseudocode
Set up 3 by 3 grid "x" goes first WHILE no one is a winner IF it is the turn of "x" find a cell that is advantageous for "x" put an "x" in that cell ELSE find a cell that is advantageous for o" put an "o" in that cell END IF Determine if there is a winner END WHILE Announce winner

Programming in Java

Two-Dimensional Arrays
Matrix with rows and columns Example: Noughts & Crosses (Tic Tac Toe) board We use 2D arrays when we use maps Use an index into the row and column The o is in the third row and second column The x is in the second row and second column

Programming in Java

Two-Dimensional Arrays
Common examples of use of 2D arrays Maps Images Rainfall (and other meteorological information) The data in the array is of the same type Can create arrays of objects

Programming in Java

Syntax & example code


arraytype[][] arrayname = new arraytype[rows][columns];

Declare a suitable two dimensional array


char[][] board = new char[3][3];

3 rows and 3 columns Start at 0 and go to 2, that is, n - 1 To initialise a location, use the indices
board[i][j] = 'x';

This means that row 3, column 2 is accessed by row: 3 - 1 = 2 column: 2 - 1 = 1 the previous example is initialised
board[2][1]= 'o'; board[1][1]= 'x';
Programming in Java 9

Syntax & example code


Can use the length constant for the length of an array Given the declaration
int[][] a = new int[20][30];

To find out how many columns there are for the third row
int result = a[2].length;

To find out how many rows there are in the array


int result = a.length;

Programming in Java

10

Syntax & example code


To step through the board to initialise it, need a nested loop
for (int row = 0; row < board.length; row++) for (int column = 0; column < board[row].length; column++) board[row][column] = ' ';

Rainfall example accessing data


int final TOWNS_MAX = 100; int final DAYS_MAX = 31; int[][]monthlyRainfall = new int[DAYS_MAX][TOWNS_MAX]; ... // print month's rainfall for 5th town for (day = 0; day < monthlyRainfall.length; day++) { System.out.println(monthlyRainfall[day][4]); }

Programming in Java

11

Style
One of the dangers of any nested code is when extra code is added It is best to use braces at all times to indicate the scope of the code, even if there is only one statement inside the loop
for (int row = 0; row < board.length; row++) { for (int column=0; column < board[row].length; column++) { board[row][column] = ' '; } }

There is less danger of miss-matching code later

What would happen in this code if the {} were not there?


for (int row = 0; row < board.length; row++) { System.out.println(row); for (int column=0; column < board[row].length; column++) { board[row][column] = ' '; } }

Programming in Java

12

Documentation
With simple nested loops it is possible to have a single comment at the top With more complex nested loops it is advisable to have a comment at the top then a number of comments through the body of the loop as needed

Programming in Java

13

Debugging
Debug writes are one way of ensuring that all the grid is accessed and that the correct locations in the grid are being changed/read Traps when designing debug writes Forgetting how much data is there
A 3X3 grid has 9 data points, a 10X10 grid has 100 data points Use print for each column value, only use println at the end of a row Put space between each value

With simple data Print the columns across top and the row at the start of each row With bulkier data Print the row and column at the start of each line then the data
that is at that location

Programming in Java

14

Debugging
With simple data (using constants for limits) or partially filled array (OK)
for (row = 0; row < MAX_ROWS; row++) { System.out.print(row); for (column = 0; column < MAX_COLS; column++) { System.out.print(anArray[row][column] + "\t" ); } System.out.println(); }

Generally we use arrays length attribute (better)


for (row = 0; row < anArray.length; row++) { for (column = 0; column < anArray[row].length; column++) { System.out.println(row + "\t" + column + ":\t" + anArray[row][column]); } }

Programming in Java

15

Debugging
One common error is to get the indices around the wrong way Rainfall example declaration
int final TOWNS_MAX = 100; int final DAYS_MAX = 31; int[][]monthlyRainfall = new int[DAYS_MAX][TOWNS_MAX]; ...

Error in code
// print month's rainfall for 5th town for (day = 0; day < DAYS_MAX; day++) { System.out.println(monthlyRainfall[4][day]); //LOGIC ERROR }

Programming in Java

16

Testing
Create test data to fill the array Check that all locations are filled with the expected values Create your own ArrayUtil class or 2D arrays to randomly
generate numbers

Create test data to check correct access of locations As in single dimension arrays, out-by-one errors can be
disastrous With multi-dimensional arrays, the out-by-one errors can affect a whole row or column

Programming in Java

17

Example The times table


A series of tables called times tables or multiplication tables There is some serious redundancy in this example. See if you can spot it as we work through it.

Programming in Java

18

Example - File TimesTable.java


public class TimesTable { private int[][] timesTable; public TimesTable(int rows, int columns) { // we're going to ignore row 0 and column 0 timesTable = new int[rows + 1][columns + 1]; for (int i = 0; i < timesTable.length; i++) for (int j = 0; j < timesTable[i].length; j++) timesTable[i][j] = i * j; } public int getResult(int row, int col) { return timesTable[row][col]; } public void printSingleTable(int row) { // times tables don't include x 0, so start from 1 for (int col = 1; col < timesTable[row].length; col++) { System.out.println(row + " x " + col + " = " + timesTable[row][col]); } } }
Programming in Java 19

Example - File TestTimesTable.java


public class TestTimesTable { Output 12 public static void main (String[] args) { 5 x 1 TimesTable timesTable = new TimesTable(12, 12); 5 x 2 5 x System.out.println(timesTable.getResult(3, 4)); 5 x 3 4 timesTable.printSingleTable(5); 5 x 5 timesTable = new TimesTable(30, 20); System.out.println(timesTable.getResult(15, 2)); timesTable.printSingleTable(15); } }
5 x 5 x 5 x 5 x 5 x 5 x 5 x 30 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x 15 x = 5 = 10 = 15 = 20 = 25 6 = 30 7 = 35 8 = 40 9 = 45 10 = 50 11 = 55 12 = 60 1 = 15 2 = 30 3 = 45 4 = 60 5 = 75 6 = 90 7 = 105 8 = 120 9 = 135 10 = 150 11 = 165 12 = 180 13 = 195 14 = 210 15 = 225 16 = 240 17 = 255 18 = 270 19 = 285 20 = 300 20

Only programmers begin counting from zero


Times tables are never created with x 0 (range is 1 - 12, not 0 - 11) Users ask for 5 x 4 without needing to shift all numbers by 1 value We accessed out array at [5][4] and not [4][3] Is why we created an array 1 row and 1 column more than needed, and why we then ignored row 0 and column 0

Programming in Java

Example - File TestTimesTable.java


What is the redundancy? In a square table, half the array stores duplicate values Storing the values of simple calculations can waste storage and
time
The example is only useful because of familiarity with the underlying concept of the multiplication table

Programming in Java

21

Example - File TicTacToe.java


/** A 3 x 3 Tic-Tac-Toe board. (Noughts and Crosses) */ public class TicTacToe { private char[][] board; private static final int ROWS = 3; private static final int COLUMNS = 3; /** * Constructs an empty board. */ public TicTacToe() { board = new char[ROWS][COLUMNS]; // fill with spaces for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = ' '; }

Programming in Java

22

TicTacToe Mutator & toString methods


/** Sets a @param @param @param */ field in board. Field must be unoccupied. i the row index j the column index player the player ('x' or 'o')

public void set(int i, int j, char player) { if (board[i][j] != ' ')


throw new IllegalArgumentException("Position occupied");

board[i][j] = player; }
/** Creates a string representation of board such as<pre> |x o| | x | | o| </pre> @return the string representation */

public String toString() { String r = ""; for (int i = 0; i < ROWS; i++) { r = r + "|"; for (int j = 0; j < COLUMNS; j++) r = r + board[i][j]; r = r + "|\n"; } return r; }
Programming in Java

23

Code - File TicTacToeTest.java


import javax.swing.JOptionPane; /** Prompts user to set positions on the board and printing out the result. */

public class TicTacToeTest { public static void main(String[] args) { char player = 'x'; TicTacToe game = new TicTacToe(); System.out.println(game); String input = JOptionPane.showInputDialog("Row for " + player + " (Cancel to exit)"); while (input != null) { // Cancelling JOptionPane returns null try { int row = Integer.parseInt(input); input = JOptionPane.showInputDialog("Column for " + player); int column = Integer.parseInt(input); game.set(row, column, player); player = player == 'x' ? 'o' : 'x'; // toggle player System.out.println(game); } catch (IllegalArgumentException e) { System.out.println(e +" Please try again"); } input = JOptionPane.showInputDialog("Row for " + player); } // end while System.out.println("Bye"); System.exit(0); // required for JOptionPane } } Programming in Java
24

Summary
Multidimensional arrays allow programmers to easily manipulate large quantities of similar data and data that humans naturally think of as occupying a grid (eg pictures) The data in a multidimensional array must have the same type It is important for the programmer to take care that declarations and access of the multidimensional array are consistent Dont mix up rows and columns!

Programming in Java

25