这是我的代码
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
您要做的就是:
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
。