Section 4.6. Example Program: CheckerBoard.java

   

4.6 Example Program: CheckerBoard.java

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.

4.6.1 CheckerBoard.java

 /*      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


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net