我正在尝试返回一个字符串,以便它不会在函数中打印,而是在主类中打印。
我试图在每个出现的字符上连接字符串,以便字符串根据输入的数字不断增长。
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;
}
}
答案 0 :(得分:0)
使用concat()方法
String str = "";
str = str.concat("blabla");
但由于您的变量名称是concat,所以请执行以下操作:
String concat = "";
concat = concat.concat("blabla");
然而,使用StringBuffer更好..
StringBuffer sb = new StringBuffer();
sb.append("blabla");
然后..对于输出,通过写:sb.toString();
返回字符串