您如何打印出一个将数组的每个元素四行的字符串

问题描述 投票:0回答:1

这是我的代码

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类编写toString方法。数组有52个元素相反,我一直将此作为输出:

1S 4S 6S 2S 8S 
8S 7S 3S 7S 
6S 8S 5S 6S
3C 3C 1C 8C 
8C 9C 4C 
java arrays methods tostring
1个回答
0
投票

您要做的就是:

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:由于Java中的字符串是不可变的,因此在循环中附加到String是一项昂贵的操作。请使用StringBuilder

© www.soinside.com 2019 - 2024. All rights reserved.