user12873296
user12873296

Reputation:

Change a method that uses System.out.print() to work with System.out.println()

I have the following code which works perfectly fine:

public static void printTrain(String[][] train, int max_height) {
    // Controls the height, 0 means the top
    for (int i = 0; i < max_height; i++) {
        // Controls the wagon index
        for (int j = 0; j < train.length; j++) {
            if (j != train.length - 1)
                System.out.print(train[j][i] + " ");
            else
                System.out.print(train[j][i]);
        }
        System.out.println();
    }
}

However, for my current project I am only allowed to use a special library (Terminal) which only allows me to use Terminal.printLine(...);.

So I have to change the method so that it only uses Terminal.printLine() <=> System.out.println().

This is how far I got:

public static void printTrain(String[][] train, int max_height) {
    StringBuilder trainGraphic = new StringBuilder();
    // Index for the height of a wagon
    for (int i = 0; i < max_height; i++) {
        // Wagon index
        for (int j = 0; j < train.length; j++) {
            if (j != train.length - 1) { // This means you need to print the connector
                trainGraphic.append(train[j][i]).append(" ++ ");
            } else {
                trainGraphic.append(train[j][i]).append("    ");
            }
        }
        Terminal.printLine("");
    }
}

No matter what I tried, it didn't work out as expected and always prints it out wrong. How do I change the code so it only uses Terminal.printLine()?

Upvotes: 2

Views: 175

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500225

Currently you're creating one StringBuilder for the whole method - but never actually printing the result of it. Instead, create one StringBuilder per line of output. It's not a big change from your original code:

public static void printTrain(String[][] train, int max_height) {
    // Controls the height, 0 means the top
    for (int i = 0; i < max_height; i++) {
        // Create a StringBuilder for this specific line
        StringBuilder builder = new StringBuilder();
        // Controls the wagon index
        for (int j = 0; j < train.length; j++) {
            if (j != train.length - 1)
                builder.append(train[j][i] + " ");
            else
                builder.append(train[j][i]);
        }
        // Print out the line we've prepared in the StringBuilder
        Terminal.printLine(builder.toString());
    }
}

Upvotes: 2

Related Questions