2 回答
TA贡献1775条经验 获得超11个赞
int lineLength = 8;
for (int i = 0; i <= 5; ++i) {
//print number
StringBuilder sb = new StringBuilder();
for (int j = i; j >= 0; j--) {
sb.append((int) Math.pow(2, j));
}
//print space
for (int spaces = lineLength - sb.length(); spaces > 0; spaces--) {
System.out.print(" ");
}
System.out.println(sb.toString());
}
还有一个更通用的例子:
public static void main(String[] args) {
int numbersToCompute = 10;
int lineLength = floydsNumber(numbersToCompute).length();
for (int i = 0; i <= numbersToCompute; ++i) {
String floydsNumber = floydsNumber(i);
for (int spaces = lineLength - floydsNumber.length(); spaces > 0; spaces--) {
System.out.print(" ");
}
System.out.println(floydsNumber.toString());
}
}
private static String floydsNumber(int i) {
StringBuilder sb = new StringBuilder();
for (int j = i; j >= 0; j--) {
sb.append((int) Math.pow(2, j));
}
return sb.toString();
}
TA贡献1779条经验 获得超6个赞
List<String> result = new ArrayList<>();
for(int i=0; i<=5; ++i) {
StringBuilder sb = new StringBuilder();
for(int j=i; j>=0; j--) {
sb.append((int)Math.pow(2, j));
}
result.add(sb.toString());
}
// You need to find out the longgest string for the padding left calculation
int length = result.get(result.size() - 1).length();
result.forEach((str -> System.out.println(padLeft(str, length))));
为填充添加直到方法:
public String padLeft(String inputString, int length) {
if (inputString.length() >= length) {
return inputString;
}
StringBuilder sb = new StringBuilder();
while (sb.length() < length - inputString.length()) {
sb.append(' ');
}
sb.append(inputString);
return sb.toString();
}
添加回答
举报