我需要在java中制作镜像三角形的帮助,就像问题中的:Creating a double mirrored triangle。然而,它需要使用递归来完成。我已经想出了如何制作两个版本的三角形:
*
**
和
**
*
但我想不出其他的路线。这部分作业没有评分,这是为了帮助我们理解,这样我们就可以弄清楚如何做镜像图像。
public static String triangle(int size) {
if (size == 0)
return "";
String dots = triangle(size - 1);
dots = dots + ".";
System.out.println(dots);
return dots;
}
//right alignment- small to big
public static String triangle2(int size) {
if (size == 0)
return "";
String dots = "";
for (int i = 0; i < size; i++){
dots = dots + ".";
}
System.out.println(dots);
return dots + triangle2(size - 1);
}
public static String triangle3(int size) {
if (size == 0)
return "";
String spaces = "";
for (int i=0; i < size-1; i++){
spaces = spaces + " ";
}
String dots = "";
dots = dots + ".";
System.out.println(spaces + dots);
return spaces + dots + triangle3(size-1);
}
发布于 2018-10-07 06:17:17
这里有一个解决方案,使用两种不同的递归方法:
public static void printMirrorTriangle(int size) {
printRow(1, size);
}
private static void printRow(int row, int size) {
System.out.println(repeat('*', row) + repeat(' ', (size - row) * 2) + repeat('*', row));
if (row < size)
printRow(row + 1, size);
}
private static String repeat(char c, int count) {
return (count == 0 ? "" : c + repeat(c, count - 1));
}
测试
printMirrorTriangle(4);
输出
* *
** **
*** ***
********
https://stackoverflow.com/questions/52683273
复制相似问题