我需要使用while循环打印这个三角形:
***** **** *** ** *
我的代码是:
new_f = numerical_f.T
new_f.columns = unique_id
它的输出是:
* ** *** **** ***** ******
答案 0 :(得分:0)
You are doing this backwards. You should start your string builder like '*****' and then replace (not append) the start with a space character. Here is an alternative using the method setCharAt:
public class TrianglePrinter {
public static void main(String[] args) {
printDescendingTriangle(5);
}
private static void printDescendingTriangle(final int a) {
StringBuilder str = initialStringBuilder(a);
int i = 0;
while(i < a){
System.out.println(str);
str.setCharAt(i,' '); // here I'm replacing the '*' with a space ' ' character
i++;
}
}
// To initialize the StringBuilder with the ***** characters with the specified length
private static StringBuilder initialStringBuilder(int a) {
StringBuilder sb = new StringBuilder(a);
for (int i = 1; i <= a; i++){
sb.append("*");
}
return sb;
}
}
Output:
*****
****
***
**
*