ITEC120-ibarland (incl. office hrs)—info—lectures—labs—hws
Nov.15 (Wed):
You can work on today's lab individually, or in pairs, as you like.
It will not be checked off, but
it's fair game for exam2.
These are the same exercises as last week, but using arrays, rather than lists. The lectures have some examples, of course.
1) a chocolate egg 2) a multi-colored pen 3) a small nugget |
ITEC120-ibarland (incl. office hrs)—info—lectures—labs—hws
(We will have lab, but nothing will be checked off. Of course, you are responsible for knowing the material.)
The following code models a rectangular world with different types of terrain.
class World { private final static int WIDTH = 7; private final static int HEIGHT = 5; char[][] terrain = new char[HEIGHT][WIDTH]; /* A 2-D array of characters. */ public static final char MOUNTAIN_CHAR = 'M'; public static final char WATER_CHAR = '~'; public static final char SWAMP_CHAR = 'o'; public static final char PLAINS_CHAR = '.'; public static final char FOREST_CHAR = '^'; /** Fill the array terrain[][] with random values. */ public void fillAllRows() { for ( int r = 0; r < terrain.length; ++r ) { fillOneRow(r); } } /** Fill one row of the array terrain[] * @param rowNum which row to fill (0..{@value HEIGHT}). */ private void fillOneRow( int rowNum ) { for ( int c = 0; c < terrain[rowNum].length; ++c ) { terrain[rowNum][c] = aRandomTerrain(); } } /** * @return A random terrain feature (as a char). */ private java.util.Random r = new java.util.Random(); public char aRandomTerrain() { int prcnt = r.nextInt(100); if (prcnt < 20) { return MOUNTAIN_CHAR; } else if (prcnt < 40) { return WATER_CHAR; } else if (prcnt < 60) { return PLAINS_CHAR; } else if (prcnt < 80) { return SWAMP_CHAR; } else if (prcnt < 100) { return FOREST_CHAR; } else { System.err.println( "Whoops, fell through to end of aRandomTerrain." ); return 'X'; } } /** * @param rowNum which row to print, in [0,{@value HEIGHT}). * @return a string representing one row of the world's terrain. * (A string of length {@value WIDTH}.) */ String oneRowToString( int rowNum ) { String mapRow = ""; for (int c = 0; c < terrain[rowNum].length; ++c ) { mapRow = mapRow + terrain[rowNum][c]; } return mapRow; } /** @return a string representing the entier world's terrtain. * (Will be {@value HEIGHT} rows, each of width {@value WIDTH}.) */ public String toString() { String map = ""; for (int rowNum = 0; rowNum < terrain.length; ++rowNum ) { map = map + oneRowToString( rowNum ) + "\n"; } return map; } } |
/** Change all 'M' mountains into '.' plains, in a single row. * @param rowNum Which row will get eroded. */ void erodeOneRow( int rowNum ) |
/** Change all 'M' mountains into '.' plains, in all of terrain[][]. */ void erodeAllRows() |
ITEC120-ibarland (incl. office hrs)—info—lectures—labs—hws
©2006, Ian Barland, Radford University Last modified 2006.Nov.16 (Thu) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |