在这里,我想避免使用该行return "";
,而是返回我输出的所有值System.out.println();
我尝试使用一种StringBuilder
方法,但是当我运行测试程序时,此方法不会输出任何内容。我猜想它StringBuilder
必须在while
循环中以不同的方式工作,但是我找不到方法!
任何建议或指导将不胜感激!
public String toString(){
int topLine = size;
int topCurrentLine = size;
int bottomLine = 1;
int bottomCurrentLine = size;
while(topCurrentLine<=size){
topCurrentLine= (size-topLine)+1;
if (topCurrentLine<=size){
for (int i = 0; i < (topCurrentLine-1); ++i){
System.out.print(".");
}
System.out.print(starMinusLine(getSandInLine(topLine), ((2*topLine-1)-getSandInLine(topLine)),false));
for (int i = 0; i < (topCurrentLine-1); ++i){
System.out.print(".");
}
topLine = topLine -1;
System.out.print("\n");
}
}
while(bottomCurrentLine>1){
bottomCurrentLine= (size-bottomLine)+1;
for (int i = 0; i < (bottomCurrentLine-1); ++i){
System.out.print(".");
}
System.out.print(starMinusLine(getSandInLine(bottomLine), ((2*bottomLine-1)-getSandInLine(bottomLine))));
for (int i = 0; i < (bottomCurrentLine-1); ++i){
System.out.print(".");
}
bottomLine = bottomLine +1;
System.out.print("\n");
}
return "";
}
这是我对StringBuilder的尝试:
public String toString(){
int topLine = size;
int topCurrentLine = size;
int bottomLine = 1;
int bottomCurrentLine = size;
StringBuilder y = new StringBuilder();
while(topCurrentLine<=size) {
topCurrentLine= (size-topLine)+1;
if (topCurrentLine<=size){
for (int i = 0; i < (topCurrentLine-1); ++i){
y.append(".");
}
y.append(starMinusLine(getSandInLine(topLine), ((2*topLine-1)-getSandInLine(topLine)),false));
for (int i = 0; i < (topCurrentLine-1); ++i){
y.append(".");
}
topLine = topLine -1;
y.append("\n");
}
}
while(bottomCurrentLine > 1) {
bottomCurrentLine= (size-bottomLine)+1;
for (int i = 0; i < (bottomCurrentLine-1); ++i){
y.append(".");
}
y.append(starMinusLine(getSandInLine(bottomLine), ((2*bottomLine-1)-getSandInLine(bottomLine))));
for (int i = 0; i < (bottomCurrentLine-1); ++i){
y.append(".");
}
bottomLine = bottomLine +1;
y.append("\n");
}
return y.toString();
}
只需打印toString。就在之前
return y.toString();
添加
System.out.println(y.toString);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句