Make a upside down triangle in java

前端 未结 3 2058
感情败类
感情败类 2020-12-04 04:26

I am trying to make the triangle I have made up side down. Tried many times, but I don\'t know how to do this.

The code I have know is:

public stati         


        
相关标签:
3条回答
  • 2020-12-04 04:45

    To flip the triangle you really just need to change the direction of iteration. Instead of going from i = 0 to i < lines you need to go down from i = lines-1 to i >= 0

    You also need to change the c to how many spaces and symbols you want to start with.

    Could look like this:

    int c = 2*lines;
    for (int i = lines-1; i>=0; i--)
    {
        for (int j = i; j < lines; j++)
        {
            System.out.print(" ");
        }
        for (int k = 1; k <= c; k++)
        {
            if (k % 2 == 0)
            {
                System.out.print(" ");
            }
            else
            {
                System.out.print(symbol);
            }
        }
    
        System.out.print("\n");
        c -= 2;
    }
    
    0 讨论(0)
  • 2020-12-04 05:01

    Reverse the first loop condition i.e. start from number of line and decrease it. Also adjust you c accordingly and make it reduce from high to low e.g. below:

        int c = 2*lines-1;
        for (int i = lines; i > 0; i--) {
            for (int j = i; j < lines; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= c; k++) {
                if (k%2==0) System.out.print(" ");
    
                else System.out.print(symbol);
            }
    
          System.out.print("\n");
          c -= 2;
        }
    
    0 讨论(0)
  • 2020-12-04 05:02
    import java.util.Scanner;
    
    public class EquilateralTraingle {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int side = sc.nextInt();
            constructEquTri(side);
    
        }
    
        private static void constructEquTri(int length) {
            // loop for each line
            for (int i = length; i > 0; i--) {
                // loop for initial spaces in each line
                for (int k = 0; k < length - i; k++) {
                    System.out.print(" ");
                }
                // loop for printing * in each line
                for (int j = 0; j < i; j++) {
    
                    System.out.print("*");
                    System.out.print(" ");
    
                }
                System.out.println();
            }
        }
    
    }
    /*Output:
        10
        * * * * * * * * * * 
         * * * * * * * * * 
          * * * * * * * * 
           * * * * * * * 
            * * * * * * 
             * * * * * 
              * * * * 
               * * * 
                * * 
                 * 
    */
    
    0 讨论(0)
提交回复
热议问题