のみ再帰を使用してV字状の印刷

都市:

私は、再帰を使用して、文字Vの形状をプリントアウトしようとしています。私は私の問題に関連し、このウェブサイトでのコードの一部を見てきましたが、大多数の利用ではなく、再帰のループ。

ここに私のコードは次のとおりです。

  public class Pattern {

    public static void main(String[] args) {
         printPattern(5);
    }
       public static void Pattern(int count, String s) {
        if (count == 0) {
            return;
        }

        System.out.print(s);
        Pattern(count - 1, s);
    }

    public static void upperhalf(int count, int max) {
        if (count == 0) {
            return;
        }

        Pattern(max - count, " ");
        Pattern(count, "* ");

        System.out.println();

        upperhalf(count - 1, max);
    }



    public static void printPattern(int n) {
        upperhalf(n, n);

    }
}

出力:

 * * * * * 
  * * * * 
   * * * 
    * * 
     * 

私が欲しいの出力:

  *       *
   *     *
    *   *
     * *
      *
ステファン:

それを解決する一つの方法。これであなたの二つの連続パターンの呼び出しを置き換えます。

    Pattern(max - count, " ");
    Pattern(1, "* ");
    Pattern(count - 2, "  ");
    Pattern(1, count > 1 ? "* " : "");        

(つまり、あなたの最初のパターン・コール、シングル*のための明示的な、より少ないあなたのアプローチに比べていくつかのスペース(2)、そして最後*)。

また、わずかexit文を変更する必要があります。

public static void Pattern(int count, String s) {
    if (count <= 0) { // <= instead of ==
        return;
    }

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=281985&siteId=1