The following program will demonstrate using a two-dimensional array. It populates a checkerboard with red pieces and black pieces where they are supposed to go and prints it to the screen. This incorporates many of the programming structures we've looked at in this chapter, including loops , conditional logic, and two-dimensional arrays.
/* File: CheckerBoard.java Purpose: demo using multidimensional arrays, loops, and conditional logic all in one. Prints a checker board. Author: E Hewitt */ import java.util.*; public class CheckerBoard { public static void main (String [] args) { // initialize some vars to loop with int x = 0; int y = 0; char board[][] = new char[8][8]; // populate red for (x = 0; x<=7; x++) { for (y = 0; y <=7; y++) { // make red if (x == 0 x == 1) board[x][y] = 'r'; // make empties else if (x > 1 && x < 6) board[x][y] = '.'; // make black else board[x][y] = 'b'; // print the current cell System.out.print(board[x][y]); // start a new row if (y == 7) {System.out.println();} } } } } //eof
The output looks like this:
rrrrrrrr rrrrrrrr ........ ........ ........ ........ bbbbbbbb bbbbbbbb
This is a useful program to play around with so that you get comfortable using arrays, nested loops, and so forth. You can imagine how this could be extended, once you're writing objects, to create the start of a real checkers game program.
Top |