我想返回一個字符串,以便它不打印在函數,而是在主類。如何連接一個字符串返回到主要在JAVA
我試圖連接出來的每個字符上的字符串,以便字符串不斷增長,具體取決於輸入的數字。
public class Main {
public static void main(String[] args) {
Diamond print = new Diamond();
output = print.print(5);
System.out.print(output);
}
}
class Diamond {
public static String print(int n) {
String concat = "";
if(!(n % 2 == 0)) {
for (int i = 1; i < n; i += 2) {
for (int k = n; k >= i; k -= 2) {
System.out.print(" ");
concat = concat.(" ");//what i am trying to do :(
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
concat = concat.("*");
}
concat = concat.("\n");
System.out.println();
}// end loop
for (int i = 1; i <= n; i += 2) {
for (int k = 1; k <= i; k += 2) {
System.out.print(" ");
}
for (int j = n; j >= i; j--) {
System.out.print("*");
}
System.out.println();
}// end loop
}
return concat;
}
}
而你的問題是? –
將'String concat'改爲'StringBuilder sb',追加到'sb.append(...)',並在最後返回'sb.toString()'。 – janos
@JoeC如何連接一個字符串以返回到JAVA主要 – learningbyexample