我试图在Java中制作一个倒三角形,但是我不知道我的代码有什么问题

public void Tr1(int height, int begin, int pos, char ch){
    for (int i = 0;i < height;i++){
        for (int k = height;k > height - 1 - i;k--){
            System.out.print(" ");
        }
        for (int j = 0;j < pos;j++){
            System.out.print(" ");
        }
        for (int v = 0;v < i*2+begin;v++){
            System.out.print(ch);
        }
        System.out.println();
    }
}


结果是:

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


我想要这个

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

最佳答案

有人问过许多类似的问题,例如I'm having trouble making a diamond shape with loops

我发布了一个递归答案,可以轻松地适应您的情况

public class InvertedTriangle {
    static int iteration = 0;
    public static void printDiamond(int n) {
        int numberOfBlanks = n - iteration;
        int numberOfStars = iteration * 2 + 1;
        String blank = new String(new char[numberOfBlanks]).replace("\0", " ");
        String star = new String(new char[numberOfStars]).replace("\0", "*");
        String row = blank + star + blank;

        iteration++;
        if (iteration < n) {
            printDiamond(n);
        }
        // printing the rows backward
        System.out.println(row);
    }

    public static void main(String[] args) {
        printDiamond(5);
    }
}


这将打印

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


提问后更新

public class InvertedTriangle {
    static int iteration = 0;

    public static void printDiamond(int n) {
        int numberOfBlanks = n - iteration;
        int numberOfInnerBlanks = iteration > 0 ? iteration * 2 - 1 : 0;
        String blank = new String(new char[numberOfBlanks]).replace("\0", " ");
        String innerBlank = new String(new char[numberOfInnerBlanks]).replace("\0", " ");
        String star = "*";
        String row = iteration == n - 1 ? blank + new String(new char[n * 2 - 1]).replace("\0", "*") + blank : iteration > 0 ? blank + star + innerBlank + star + blank : blank + star + blank;

        iteration++;
        if (iteration < n) {
            printDiamond(n);
        }
        // printing the rows backward
        System.out.println(row);
    }

    public static void main(String[] args) {
        printDiamond(10);
    }
}


这将打印

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

08-18 01:01