java打印带有整数的反向triagle s

时间:2016-04-02 10:16:17

标签: java

我正在尝试实现一个java代码,以反向顺序打印三角形。这是我的代码。

public void drawPatternC(int num) {
 //Loop through the lines from 1 to n
 System.out.println("Pattern .C:" + "\u21B5");
 for (int i = 1; i <= num; i++) {
  // printing spaces, 2 at a time from j=1 to j= num-i 
  for (int j = 1; j <= (num - i); j++) {
   System.out.print(" . ");
  }

  //Printing number increamentally from 1 to line number j
  for (int j = 1; j <= i; j++) {
   System.out.print(j + ". ");
  }
  System.out.println("\u21B5");
 }

}

我希望结果看起来像

....1
...21
..321
.4321

但是我得到了一个不同的我需要帮助

3 个答案:

答案 0 :(得分:0)

你没有用你的第二个循环以正确的方式循环

替换

for (int j = 1; j <= i; j++)

for (int j = i; j > 0; j--)

校正

public void drawPatternC(int num) {         
    for (int i = 1; i <= num; i++) {
        for (int j = 1; j <= (num - i); j++) {
            System.out.print(" . ");
        }

        //Printing number increamentally from 1 to line number j
        for (int j = i; j > 0; j--) {
            System.out.print(j+". ");
        }
        System.out.println();
    }
}

输出

 .  .  .  . 1. 
 .  .  . 2. 1. 
 .  . 3. 2. 1. 
 . 4. 3. 2. 1. 
5. 4. 3. 2. 1. 

答案 1 :(得分:0)

此代码应该可以解决您的问题。它更加简化了。

public void drawPatternC(int num)
{
    for(int i=1;i<num;i++)
    {
        for(int j=num;j>i;j--)
        {
            System.out.print("."); 
        }
        for(int k=i;k>0;k--)
        {
            System.out.print(k);
        }
        System.out.println();
    }
}

OUTPUT(当num = 5时):

.... 1

... 21

... 321

0.4321

答案 2 :(得分:0)

我已对您的代码进行了一些更改

public static void drawPatternC(int num) {
    //Loop through the lines from 1 to n
    System.out.println("Reverse triangle:");
    for (int i = 1; i <= num; i++) {
        // printing spaces, 2 at a time from j=1 to j= num-i
        for (int j = 1; j <= (num - i + 1); j++) {
            System.out.print(".");
        }

        //Printing number increamentally from 1 to line number j
        for (int j = 1; j <= i; j++) {
            System.out.print(j);
        }
        System.out.println("");
    }
}