// APS101, Winter 2009: Lecture 27 (Mar. 17) // // Review: last time we began looking at 2-Dimensional Arrays. // 1-D array: int[] // 2-D array: int[][] // it's useful to think of a 2-D array as a 1-D array that stores // other 1-D arrays - the principles are the same. // (e.g., you still access the contents of an array using indices.) int[][] a = new int[3][]; a.length a[0] // why is it null? a[0] = new int[10]; a a[0].length; a[1] = new int[5]; // exercise: make a 2-D array that stores the following: // 1 2 3 // 4 5 6 int[][] a = new int[2][3]; for (int i = 0; i <= 1; i++) { // for each of the 2 rows for (int j = 0; j <= 2; j++) { // for each of the 3 columns a[i][j] = j + 1 + 3 * i; } } // now, if we want to print the contents of an array: for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } // for the next few lectures, we will write a Tic-Tac-Toe game, // in order to practice everything we've learned. // (this will help you with Assignment 3!) // the game will be both in text mode, and with a GUI. // first, we will need to develop the game "engine", which is the // class that contains the "behind the scenes" methods that do all the work. // think about how to represent the tic-tac-toe game... // we need a square grid to put an 'X' or an 'O' on it. // char[][] a: a is an array of char arrays // (take a look at TicTacToe.java) TicTacToe t = new TicTacToe(); t t.board // for now, we have no other way of seeing the game // now, we want to be able to put an 'X' or an 'O' t.setMark('X', 0, 0); t.board t.setMark('O', 1, 1); t.board t.setMark('X', 1, 1); // doesn't change anything! t.board // now, we need to visualize the game... for example: // empty grid: | | - - - | | - - - | | // or: X| | - - - O|O| - - - | | // we need to write a toString() method for this.