鉴于数字5,我正在尝试解决此问题,我们显示:
*
*****
*********
*****
*
以此类推。所以您给它一个数字,并像上面一样为您设置格式。我试图使用下面的代码来解决它,但我看不出代码中的问题所在。
public class Exe01 {
public static String space = "";//global space var
public static String ast = "";//global * var
public static String adjustAst(int numOfAst) {
Exe01.ast = "";
for (int i = numOfAst; i > 0; i--) {
Exe01.ast+="*";
}
return Exe01.ast;
}
public static String adjustSpaces(int numOfSpaces) {
Exe01.space = "";
for (int i = numOfSpaces; i > 0; i--) {
Exe01.space = Exe01.space + " ";
}
return Exe01.space;
}
public static void showAst(int num) {
if (num <= 0 || num % 2 == 0)
System.out.println("arg to the function need to be positive and odd");
else if (num == 1)
System.out.println("*");
else {
int mid = (int) (num / 2);
int numberOfSpaces = num - 1;
for (int i = 0; i < num; i++) {
int k = 0;
if (i < mid) {
k = k * 2 + 1;
System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
numberOfSpaces = numberOfSpaces - 2;
} else if (i == mid) {
numberOfSpaces = 0;
k = k * 2 + 1;
System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
numberOfSpaces = numberOfSpaces + 2;
} else {
k = k - 4;
System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
numberOfSpaces = numberOfSpaces + 2;
}
}
}
}
public static void main(String args[]) {
Exe01.showAst(5);
}
}
在编译时,它给了我:
*
*
*