[英]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 類編寫 toString 方法。 該數組有 52 個元素,相反,我一直將其作為輸出:
1S 4S 6S 2S 8S
8S 7S 3S 7S
6S 8S 5S 6S
3C 3C 1C 8C
8C 9C 4C
使用 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);
}
您所要做的就是:
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] + " ";
}
另外:在循環中附加到String
是一項昂貴的操作,因為 java 中的字符串是不可變的。 請改用StringBuilder
。 在這里閱讀更多。
我不明白w-=-1
超過w++
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.