Java Tutorial Lesson 06: Program arguments and arrays

From Erlands Wiki

Jump to: navigation, search

You start with a Room class like this:

public class Room {
    private String title;
    public Room(String title) {
        this.title = title;
    }
    public void print() {
        System.out.println("----------");
        System.out.println("|        |");
 
        // Print left wall
        System.out.print("|");
 
        // Calculate number of spaces
        int noOfSpaces = 8-title.length();
 
        // Print spaces before text
        for(int i=0;i<noOfSpaces/2;i++) {
            System.out.print(" ");
        }
 
        System.out.print(title);
 
        // Print spaces after text
        for (int i = 0; i < noOfSpaces-noOfSpaces/2; i++) {
            System.out.print(" ");
        }
 
        // Print right wall and change line
        System.out.println("|");
 
        System.out.println("|        |");
        System.out.println("----------");
    }
}

Your work is to create a “Game” class that can be called as:

java Game kalle ola nicklas

And then give an output like:

Lesson 6
 
----------
|        |
| kalle  |
|        |
----------
----------
|        |
|  ola   |
|        |
----------
----------
|        |
|nicklas |
|        |
----------

It shall be possible to have different number of parameters, in the example above we just use the 3 parameters “kalle”, “ola”, “nicklas” as an example.

Some optional things to try:

  1. Read the texts from a file and take the filename as parameter instead of sending the text strings themself as parameters
  2. If the text string is longer than 8 characters you can try to cut it so the room wall still look nice
  3. If the text string is longer than 8 characters you can try to add a line break and continue the text on the next line


Personal tools