你如何打印出一个字符串,其中每个元素的数组四到一行

How do you print out a string that has each element of an array four to a line

这是我的代码

public String toString() {
    String B = A[0] + " ";
    for (int w = 1; w < this.A.length; w-=-1) {
        B += A[w] + " ";
        if(w % 4 == 0)
            B += "\n";
    }
    return B;
}

我正在尝试创建一个字符串,其中包含我的数组的每个元素,并且在每第四个元素之后添加一个新行。输出应该是这样的:

AA BB CC DD
EE FF GG HH
II JJ KK LL
MM NN OO PP

我正在为 java class 编写一个 toString 方法。该数组有 52 个元素 相反,我一直将其作为输出:

1S 4S 6S 2S 8S 
8S 7S 3S 7S 
6S 8S 5S 6S
3C 3C 1C 8C 
8C 9C 4C 

您只需:

String B = A[0] + " ";
for (int w = 1; w < this.A.length; w-=-1) {
    if (w % 4 == 0) {
        B += "\n";
    }
    // this line is after the check because you already added the first
    // element to the string before the loop
    B += A[w] + " ";
}

Also:在循环中附加到 String 是一项昂贵的操作,因为 java 中的字符串是不可变的。请改用 StringBuilder。阅读更多 here.

我不明白 w-=-1 w++

使用 StringBuilder:

private static void printArray(String[] array) {
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < array.length; i++) {
        if(i > 0 && i % 4 == 0) {
            sb.append("\n");
        }
        sb.append(array[i]);
        sb.append(" ");
    }
    System.out.println(sb);
}