我正在尝试获得此输出:
123454321
1234 4321
123 321
12 21
1 1
我先尝试过这样做:
12345
1234
123
12
1
然后,放一个'\ t'并将其放在上面的旁边:
4321
4321
321
21
1
答案 0 :(得分:1)
以下代码给出了您提到的输出
package com.hello;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
printNumbers(5,5);
}
private static void printNumbers(int max,int iteration)
{
String line ="";
int NoOfSpaces = (max-iteration)*2 -1;
if(iteration == 0)
return;
for(int i=1;i<=iteration;i++)
line = line+i;
for(int i =0;i<NoOfSpaces;i++)
line = line+" ";
if(max != iteration)
line = line +iteration;
for(int i=iteration-1;i>=1;i--)
line = line +i;
System.out.println(line);
printNumbers(max,--iteration);
}
}
如果您有任何其他问题,请告诉我。
答案 1 :(得分:0)
可以使用以下代码递归解决问题:
public static void recurseForward(int to, int space) {
if (to == 0) {
return;
}
for (int i = 1; i <= to; i++) {
System.out.print(i);
}
for (int i = 0; i < space; i++) {
System.out.print(" ");
}
recurseBackward(to, space);
}
public static void recurseBackward(int from, int space) {
for (int i = 0; i < space; i++) {
System.out.print(" ");
}
for (int i = from; i > 0; i--) {
System.out.print(i);
}
System.out.println("");
recurseForward(from - 1, space + 1);
}
public static void main(String[] args) {
recurseForward(5, 0);
}