本文介绍了使用递归Java镜像三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助在 java 中制作镜像三角形,就像问题中的一样:创建双镜像三角形.然而,它需要使用递归来完成.我已经想出了如何制作三角形的两个版本:
*
**
和
**
*
但我无法弄清楚其他对齐方式.作业的那部分没有评分,是为了帮助我们理解,以便我们弄清楚如何做镜像.
I need help making a mirrored triangle in java like in the question: Creating a double mirrored triangle.However it needs to be done using recursion. I figured out how to make two versions of the triangle already:
*
**
and
**
*
But I cant figure out the other alignments. That part of the assignment is not graded, it is to help our understanding so we can figure out how to do the mirrored image.
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);
}
推荐答案
这是一种解决方案,使用两种不同的递归方法:
Here is one solution, using two different recursive methods:
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);
输出
* *
** **
*** ***
********
这篇关于使用递归Java镜像三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!