【问题标题】:How to print dot pattern in correct way?如何正确打印点阵图案?
【发布时间】:2014-07-07 18:24:42
【问题描述】:

这就是我所拥有的。

当我在 makePattern(int size) 中省略其中一个 makePattern(size - 1) 时,我得到了下半部分。但我不知道如何获得上半部分。

public void makePattern(int size){

    stringList = new ArrayList<String>();
    if (size == 0){
        System.out.print("");
    }
    else{

        makePattern(size - 1);
        System.out.println(dotString(size));
        makePattern(size - 1);

    }
}

辅助方法

  public String dotString(int x){
    if (x == 1){
        return ".";
    }
    else{

        return dotString(x - 1) + ".";
    }
}

主要测试方法:

   public static void main(String[] args) {

    Pattern rP = new Pattern();

    int sizePt = 5;
    System.out.println();
    for(int i=1; i<=sizePt; i++) {
        System.out.println("pattern " + i);
        rP.makePattern(i);
        ArrayList<String> pattern = rP.getStringList();
        for(int j = 0; j < pattern.size() ; j++)
            System.out.println(pattern.get(j));

        System.out.println();
    }

我得到的输出:

模式 1

.

模式 2

.

..

.

模式 3

.

..

.

...

.

..

.

我想要的输出是:

即makePattern(3)

.

..

...

..

.

【问题讨论】:

  • 您需要递归执行此操作吗?
  • 这不是直接相关的,但应该会有所帮助:我为java初学者写了一个short debugging tutorial。关于打印的部分可能会帮助您了解代码的流程。
  • “请帮助”不是问题。 keyser 关于“学习如何调试”的非常礼貌的建议可能是您现在可以获得的最佳帮助。一般来说,有比 StackOverflow 更好的调试技术。
  • 我想在没有循环的情况下递归地执行此操作。

标签: java


【解决方案1】:

每次您进行递归调用时,您每次都在创建一个完整的模式。这不是你想要的。相反,您希望在每个函数调用中制作 一半 模式。上半部分或下半部分。


所以最后你想要一个递归函数来做这个:

.  
..  
...  

以及执行此操作的递归函数(可以使用相同的函数同时执行)

...
..
.

以及将它们联系在一起的函数。


您可以采取的另一种方法是每个函数只有一个递归调用。

创建一个在此模式上打印变体的函数

...
....
.....
....
...

然后这样称呼它

makePattern(**insert args here**)
{
    //handle base case
    System.out.println(dotString(size));
    makePattern(**insert args here**)
    System.out.println(dotString(size));
}

【讨论】:

  • @Pshemo 哎呀,我添加了伪代码。我还能获得 +1 吗?
  • 我不知道如何开始另一半
  • @user3792115 您可以直接从 main 方法或非递归辅助函数中创建
【解决方案2】:

我的 2 美分:

public void makePattern(int size, int direction)
{
    if (size == 0)
        return; // quit recursion when we're down to 0

    // start out recursively calling back until we reach 0 with -1 direction
    // that will print AFTER the calls to the negative direction so the last
    // recursive call prints FIRST
    if (direction <= 0)
        makePattern(size - 1, -1);

    // all the makePatterns and prints for the lower direction will happen
    // and return back to here where we call print for the original number
    // passed
    System.out.println(dotString(size));

    // now we recursively call with direction = 1 AFTER printing so the last
    // recursive call prints LAST
    if (direction >= 0)
        makePattern(size - 1, 1);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 2021-05-14
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多