使用递归打印空白区域

时间:2016-11-14 01:58:07

标签: java for-loop recursion whitespace padding

所以我正在编写一个程序,它将打印一个文本三角形,我在这个循环中用于在该递归方法中打印空白区域。我想得到另一个递归方法,它将打印白色空间而不用for循环。现在,我只是使用一个处理文本的递归方法,但我不想在我的方法中使用循环结构。我知道如何使用for循环这样做。

for (int i = 0; i < indent; i++) { //padding
  System.out.print(' ');
} //for

但是,我试图使用递归来复制相同的东西。 我能够提出自己的代码,但输出错误。

public static void print(String str, int indent, int leftLen, int rightIdx) {
 //    for (int i = 0; i < indent; i++) { //this works perfectly fine
//      System.out.print(' '); // i want to do this recursively.
//    } //for

  whiteSpace(indent);
// ....... some more coding that deals with the text

}

public static void whiteSpace(int indent) {
  int index = 0;
  whiteSpaceHelper(index, indent);
 }

public static void whiteSpaceHelper(int index, int indent) {
if(index < indent) {
  System.out.println(' ');
  index++;
  whiteSpaceHelper(index, indent);
}

我的程序使用递归方法打印类似的内容:

enter image description here

我想要的输出是for循环:

enter image description here

是否可以使用递归来做类似的事情。任何人都可以指出我的whiteSpace方法中的逻辑错误?我只需要指针就能让我朝着正确的方向前进。我会提供更多细节,如果这可以帮助你帮助我。任何其他改进或技术将不胜感激。

0 个答案:

没有答案