简体   繁体   English

如何使用for循环在Java中创建向后三角形

[英]How do i create a backward triangle in java using for loops

I need to make a triangle that looks like this 我需要做一个看起来像这样的三角形

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

Currently i have a working one that looks like 目前我有一个工作的样子

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

using the loop : 使用循环:

public static void standard(int n)
   {
      for(int x = 1; x <= n; x++)
      {
         for(int c = 1; c <= x; c++)
         {
            System.out.print("*");
         }
         System.out.println();
      }
   }

How do i go about making this work 我该如何进行这项工作

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

Here is my attempt: 这是我的尝试:

public static void backward(int n) 
{ 
    for(int x = 7; x <= n; x++) 
    { 
        for(int y = 1; y >= x; y--) 
        {
            if (x >= y) 
            { 
                System.out.print("*");
            } 
            else 
            {
                System.out.print("");
            }
         }
         System.out.println();
    }
}

On every line print n chars: if index c < n - x , print space, otherwise print asterisk: 在每行上打印n字符:如果索引c < n - x ,则打印空间,否则打印星号:

for (int x = 1; x <= n; x++) {
    for (int c = 0; c < n; c++) 
        System.out.print(c < n - x ? ' ' : '*');    
    System.out.println();
}

Output (n = 6): 输出(n = 6):

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

public static void standard(int n)
   {
      for(int x = 1; x <= n; x++)
      {

New Code Here 这里的新代码

         for (int b = 0; b <= (n - x); b++)
            System.out.print(" ");

This code adds spaces before adding stars. 此代码在添加星号之前添加空格。 since a triangle is rect over 2, we know that total length will be n each time, and we are just making the others spaces to only show triangle 由于三角形在2上正切,我们知道每次的总长度为n,因此我们仅使其他空格仅显示三角形

         for(int c = 1; c <= x; c++)
         {
            System.out.print("*");
         }
         System.out.println();
      }
   }
void triangle(int n) {

        // create first line
        StringBuffer out = new StringBuffer(2 * n + 1);
        for (int i = 0; i < n - 1; ++i) {
            out.append(' ');
        }
        out.append('*');

        // repeatedly remove a space and add a star
        while (n-- > 0) {
            System.out.println(out);
            out.deleteCharAt(0);
            out.append("*");
        }
    }

Just change the loop so that x denotes the number of spaces and print that number of spaces first and then print the the chars missing to fill the line: 只需更改循环,以使x表示空格数,然后先打印该空格数,然后打印缺少的字符以填充该行:

for (int x = n-1; x >= 0; x--) {
    for (int c = 0; c < x; c++) {
        System.out.print(" ");
    }
    for (int c = x; c < n; c++) {
        System.out.print("*");
    }
    System.out.println();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM