Java Tutorial Lesson 09: Matrices and objects
From Erlands Wiki
You have this “Room” class:
public class Room { private String title; private static final int ROOM_WIDTH=10; private static final int ROOM_HEIGHT=5; public Room(String title) { this.title = title; } public char[][] getData() { char [][] data = new char[ROOM_HEIGHT][ROOM_WIDTH]; data[0] = new String("----------").toCharArray(); data[1] = new String("| |").toCharArray(); // Print left wall data[2][0] = '|'; // Calculate number of spaces // (Remove text and walls from total width) int noOfSpaces = ROOM_WIDTH-title.length()-2; // Print spaces before text int i; for(i=1;i<=noOfSpaces/2;i++) { data[2][i] = ' '; } // Print the text // (Make sure we have place for right wall (ROOM_WIDTH-1)) for(int k=0;k<title.length() && i<ROOM_WIDTH-1;k++,i++) { data[2][i] = title.toCharArray()[k]; } // Print spaces after text // (Make sure we have place for right wall (ROOM_WIDTH-1)) for (int r=noOfSpaces/2;r < noOfSpaces && i<ROOM_WIDTH-1; r++,i++) { data[2][i] = ' '; } // Print right wall and change line data[2][9] = '|'; data[3] = new String("| |").toCharArray(); data[4] = new String("----------").toCharArray(); return data; } }
Your work is to create a “Game” class that can be called as:
java Game 3 3
The output when running the Game class should look as follows:
Lesson 9 ------------------------------ | || || | | 1 || 2 || 3 | | || || | ------------------------------ ------------------------------ | || || | | 4 || 5 || 6 | | || || | ------------------------------ ------------------------------ | || || | | 7 || 8 || 9 | | || || | ------------------------------
Some leads:
- The print order when 3 3 is given as parameters are:
- The first line of room 1
- The first line of room 2
- The first line of room 3
- The second line of room 1
- The second line of room 2
- The second line of room 3
- And same logic for the rest of lines of room 1-3
- The first line of room 4
- The first line of room 5
- The first line of room 6
- The second line of room 4
- And continue in the same way until the whole map has been printed
- Its a good idea to do the implementation in two steps, first create a matrix with all the room, then step through the matrix and print the rooms
- To make it easier you can assume that all rooms have the same size. This makes it possible to get the size of a room by checking the size of the first room in position 0,0 in the following way:
Room r = roomMatrix[0][0]; int height = r.getData().length; // Number of lines in room int length = r.getData()[0].length; // Number of columns in first line of room
