简体   繁体   English

将使用 System.out.print() 的方法更改为与 System.out.println() 一起使用

[英]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(...);但是,对于我当前的项目,我只允许使用一个特殊的库(终端),它只允许我使用Terminal.printLine(...); . .

So I have to change the method so that it only uses Terminal.printLine() <=> System.out.println().所以我必须改变方法,使它只使用 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()?如何更改代码使其仅使用 Terminal.printLine()?

Currently you're creating one StringBuilder for the whole method - but never actually printing the result of it.目前您正在为整个方法创建一个StringBuilder - 但从未真正打印它的结果。 Instead, create one StringBuilder per line of output.相反,每行输出创建一个StringBuilder 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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM