我在递归地打印出包含空格和星号的三角形时遇到了麻烦。显然,可能需要使用stringbuffer或stringbuilder来计算正确的空格和星号数量,但是我有点困难。这两个三角形应该看起来像:
****
***
**
*
和
*
**
***
****
public static String printTriangle(int num)
{
if (num == 0) {
return "";
}
String dots = "";
for (int i = 0; i < num; i++) {
dots = dots + "*";
}
System.out.println(dots);
return printTriangle(num-1) + dots;
}
public static String printTriangle2(int num) {
if (num == 0) {
return "";
}
String dots = printTriangle2(num-1);
dots = dots + ".";
String spaces = "";
for (int i = 0; i < num; i++) {
spaces = spaces + " ";
}
String line = spaces + dots;
System.out.println(line);
return line;
}
这是我到目前为止所拥有的。任何帮助将不胜感激。
这是当前的输出:
****
***
**
*
.
..
...
....
答案 0 :(得分:2)
这是一个相当简单的实现:
static void printTriangle(int n, int len)
{
if(n == len) return;
printRow(n, len);
printTriangle(n+1, len);
printRow(n, len);
}
static void printRow(int n, int len)
{
for(int i=0; i<n; i++) System.out.print(" ");
for(int i=n; i<len; i++) System.out.print("*");
System.out.println();
}
测试:
printTriangle(0, 4);
输出:
****
***
**
*
*
**
***
****
尽管我喜欢这样:
static void printTriangle(String s)
{
if(!s.contains("*")) return;
System.out.println(s);
printTriangle(" " + s.replaceFirst("\\*", ""));
System.out.println(s);
}
致电
printTriangle("****");
答案 1 :(得分:1)
尝试下面的代码并用step=0
调用
printTriangle(4,0)
printTriangle2(4,0)
public static String printTriangle(int num, int step)
{
if (num == 0) {
return "";
}
String ast = "";
for (int i = 0; i < num; i++) {
ast = ast + "*";
}
String sps = "";
for (int i = 0; i < step; i++) {
sps = sps + " ";
}
System.out.println(sps+ast);
return printTriangle(num-1, step+1) ;
}
public static String printTriangle2(int num, int step)
{
if (num == 0) {
return "";
}
String ast = "";
for (int i = 0; i <= step; i++) {
ast = ast + "*";
}
String sps = "";
for (int i = 0; i < num; i++) {
sps = sps + " ";
}
System.out.println(sps+ast);
return printTriangle2(num-1, step+1) ;
}