【问题标题】:Printing *s as triangles in Java?在Java中将*s打印为三角形?
【发布时间】:2012-12-26 23:31:48
【问题描述】:

我在 Java 课程中的任务是制作 3 个三角形。一个左对齐,一个右对齐,一个居中。我必须为什么类型的三角形制作一个菜单,然后输入需要多少行。三角形必须是这样的

*
**
***
****


   *
  **
 ***
****


  *
 ***
*****

到目前为止,我能够制作左对齐的三角形,但我似乎无法获得其他两个。我尝试使用谷歌搜索,但没有任何结果。任何人都可以帮忙吗?到目前为止我有这个。

import java.util.*;
public class Prog673A
{
    public static void leftTriangle()
    {
        Scanner input = new Scanner (System.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i <= x; i++)
            {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
    public static void rightTriangle()
    {
        Scanner input = new Scanner (System.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i >= x; i--)
            {
                System.out.print(" ");
            }
            System.out.println("*");
        }
    }
    public static void centerTriangle()
    {

    }
    public static void main (String args [])
    {
        Scanner input = new Scanner (System.in);
        System.out.println("Types of Triangles");
        System.out.println("\t1. Left");
        System.out.println("\t2. Right");
        System.out.println("\t3. Center");
        System.out.print("Enter a number: ");
        int menu = input.nextInt();
        if (menu == 1)
            leftTriangle();
        if (menu == 2)
            rightTriangle();
        if (menu == 3)
            centerTriangle();
    }
}

样本输出:

Types of Triangles
1.  Left
2.  Right
3.  Center
Enter a number (1-3):  3
How many rows?: 6

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

【问题讨论】:

    标签: java loops


    【解决方案1】:

    提示:对于每一行,您需要首先打印一些空格,然后然后打印一些星号。 每行空格数应减少一个,而星数应增加。

    对于居中的输出,每行增加两个的星数。

    【讨论】:

      【解决方案2】:

      Ilmari Karonen 有很好的建议,我想概括一下。一般来说,在你问“我怎样才能让电脑来做这件事?”之前。问“会怎么做?”

      所以,如果有人给你一个空的 Word 文档并要求你创建三角形,你会怎么做呢?无论您想出什么解决方案,通常都不难将其翻译成 Java(或任何其他编程语言)。它可能不是最好的解决方案,但(希望如此!)它会起作用,它可能会为您指明更好的解决方案。

      例如,也许你会说你要输入基数,然后向上一行,然后输入下一个最高的行,等等。这表明你可以在 Java 中做同样的事情——创建一个列表字符串,从底部到顶部,然后将它们反转。这可能表明您可以按相反的顺序创建它们,然后不必颠倒它们。然后 that 可能会建议您不再需要该列表,因为您只需按照相同的顺序创建和打印它们 - 此时您基本上已经想出了 Ilmari卡罗宁的建议。

      或者,也许你会想出另一种方法——也许你会更直接地想出 Ilmari Karonen 的想法。无论如何,它应该可以帮助您解决这个问题和许多其他问题。

      【讨论】:

        【解决方案3】:

        左对齐三角形- * **



        from above pattern we come to know that-
        1)we need to print pattern containing n rows (for above pattern n is 4).
        2)each  row contains star and no of stars i each row is incremented by 1.
        So for Left alinged triangle we need to use 2 for loop.
        1st "for loop" for printing n row.
        2nd  "for loop for printing stars in each rows. 
        
        
         Code for  Left alinged triangle-
        
         public static void leftTriangle()
        {
               /// here  no of rows is 4
         for (int a=1;a<=4;a++)// for loop for row
         {   
         for (int b=1;b<=a;b++)for loop for column
         {
         System.out.print("*");
         }
        
        System.out.println();}
        }
        

        直角三角形- *
        **



        from above pattern we come to know that-
        1)we need to print pattern containing n rows (for above pattern n is 4).
         2)In each  row we need to print spaces followed by a star & no of spaces            in each row is decremented by 1.
         So for Right alinged triangle we need to use 3 for loop.
         1st "for loop" for printing n row.
         2nd  "for loop for printing spaces.
         3rd "for loop" for printing stars.
        
        Code for Right alinged triangle -
        
        public void rightTriangle()
        {
            // here 1st print space and then print star
          for (int a=1;a<=4;a++)// for loop for row
         { 
         for (int c =3;c>=a;c--)// for loop fr space
         {  
         System.out.print(" ");
         }
         for (int d=1;d<=a;d++)// for loop for column
         { 
         System.out.print("*");   
         }
         System.out.println(); 
         }
         }
        

        中心三角形- *
        * *



        从上面的模式我们知道- 1)我们需要打印包含 n 行的模式(对于上述模式 n 为 4)。 2)最初在每一行中,我们需要打印空格,后跟一个星号,然后再打印一个空格。开始时每行中的空格数减 1。 所以对于直角三角形,我们需要使用 3 for 循环。 第一个用于打印 n 行的“for 循环”。 第二个“用于打印空间的for循环。 用于打印星星的第三个“for 循环”。

        中心三角形的代码-

        public  void centerTriangle()
        {   
        for (int a=1;a<=4;a++)// for lop for row
        {   
        for (int c =4;c>=a;c--)// for loop for space
        {  
        System.out.print(" ");
        }
        for (int b=1;b<=a;b++)// for loop for column
        {
        System.out.print("*"+" ");
        }
        System.out.println();}
        }
        

        打印所有 3 种图案的代码 - 公共课空间4 { 公共静态无效leftTriangle() { /// 这里的行数是 4 for (int a=1;a for (int b=1;b

        System.out.println();}
        }
        
        public static void rightTriangle()
        {
            // here 1st print space and then print star
          for (int a=1;a<=4;a++)// for loop for row
         { 
         for (int c =3;c>=a;c--)// for loop for space
         {  
         System.out.print(" ");
         }
         for (int d=1;d<=a;d++)// for loop for column
         { 
         System.out.print("*");   
         }
         System.out.println(); 
         }
         }
        
        public static void centerTriangle()
        {   
        for (int a=1;a<=4;a++)// for lop for row
        {   
        for (int c =4;c>=a;c--)// for loop for space
        {  
        System.out.print(" ");
        }
        for (int b=1;b<=a;b++)// for loop for column
        {
        System.out.print("*"+" ");
        }
        System.out.println();}
        }
        public static void main (String args [])
        {
        space4 s=new space4();
        s.leftTriangle();
        s.rightTriangle();
        s.centerTriangle();
        }
        }
        

        【讨论】:

          【解决方案4】:
          package apple;
          
          public class Triangle {
              private static final int row = 3;
          
              public static void main(String... strings) {
                  printLeftTriangle();
                  System.out.println();
                  printRightTriangle();
                  System.out.println();
                  printTriangle();
              }
          
              // Pattern will be
              // *
              // **
              // ***
              public static void printLeftTriangle() {
                  for (int y = 1; y <= row; y++) {
                      for (int x = 1; x <= y; x++)
                          System.out.print("*");
                      System.out.println();
                  }
              }
          
              // Pattern will be
              //   *
              //  **
              // ***
              public static void printRightTriangle() {
                  for (int y = 1; y <= row; y++) {
                      for (int space = row; space > y; space--)
                          System.out.print(" ");
                      for (int x = 1; x <= y; x++)
                          System.out.print("*");
                      System.out.println();
                  }
              }
          
              // Pattern will be
              //   *
              //  ***
              // *****
              public static void printTriangle() {
                  for (int y = 1, star = 1; y <= row; y++, star += 2) {
                      for (int space = row; space > y; space--)
                          System.out.print(" ");
                      for (int x = 1; x <= star; x++)
                          System.out.print("*");
                      System.out.println();
                  }
              }
          }
          

          【讨论】:

            【解决方案5】:

            这是普通三角形:

            for (int i = 0; i < 5; i++) {
                for (int j = 5; j > i; j--) {
                    System.out.print(" ");
                }
                for (int k = 1; k <= i + 1; k++) {
                    System.out.print(" *");
                }
                System.out.print("\n");
            }
            

            输出:

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

            这是左三角形,只是在打印*之前删除了空格:

            for (int i = 0; i < 5; i++) {
                for (int j = 5; j > i; j--) {
                    System.out.print(" ");
                }
                for (int k = 1; k <= i + 1; k++) {
                    System.out.print("*");
                }
                System.out.print("\n");
            }
            

            输出:

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

            【讨论】:

              【解决方案6】:

              1) 正三角形

              package test1;
              
              
               class Test1 {
              
                   public static void main(String args[])
                   {
                       int n=5;
                   for(int i=0;i<n;i++)
                   {
              
                       for(int j=0;j<=n-i;j++)
                       {
              
                           System.out.print(" ");
                       }
              
                       for(int k=0;k<=2*i;k++)
                       {
                       System.out.print("*");
                       }
              
                       System.out.println("\n");
              
                   }
              
                   }
              

              2) 直角三角形

              package test1;
              
              
               class Test1 {
              
                   public static void main(String args[])
                   {
                       int n=5;
                   for(int i=0;i<n;i++)
                   {
              
                       for(int j=0;j<=n-i;j++)
                       {
              
                           System.out.print(" ");
                       }
              
                       for(int k=0;k<=i;k++)
                       {
                       System.out.print("*");
                       }
              
                       System.out.println("\n");
              
                   }
              
                   }
              
              
              }
              
                   }
              

              3) 左角三角形

              package test1;
              
              
               class Test1 {
              
                   public static void main(String args[])
                   {
                       int n=5;
                   for(int i=0;i<n;i++)
                   {
              
                       for(int j=0;j<=i;j++)
                       {
              
                           System.out.print("*");
                       }
              
                       System.out.println("\n");
              
                   }
              
                   }
              
              
              }
              

              【讨论】:

                【解决方案7】:

                我知道这已经很晚了,但我想分享我的解决方案。

                public static void main(String[] args) {
                    String whatToPrint = "aword";
                    int strLen = whatToPrint.length(); //var used for auto adjusting the padding
                    int floors = 8;
                    for (int f = 1, h = strLen * floors; f < floors * 2; f += 2, h -= strLen) {
                        for (int k = 1; k < h; k++) {
                                System.out.print(" ");//padding
                            }
                        for (int g = 0; g < f; g++) {
                            System.out.print(whatToPrint);
                        }
                        System.out.println();
                    }
                }
                

                三角形左侧的空格会根据您要打印的字符或单词自动调整。

                如果 whatToPrint = "x"floors = 3 会打印出来

                x xxx xxxxx 如果没有自动调整空间,会是这个样子(whatToPrint = "xxx"同层数)

                xxx xxxxxxxxx xxxxxxxxxxxxxxx

                所以我添加了一个简单的代码,这样就不会发生了。

                对于左半边三角形,只需将strLen * floors 更改为strLen * (floors * 2) 并将f +=2 更改为f++

                对于右半三角形,只需删除此循环for (int k = 1; k &lt; h; k++) 或将h 更改为0,如果您选择删除它,请不要删除System.out.print(" ");

                【讨论】:

                  【解决方案8】:

                  对于直角三角形,对于每一行:

                  • 首先:需要打印0到rowNumber - 1 - i之间的空格。
                  • 第二:需要将\*rowNumber - 1 - i打印到rowNumber

                  注意:i 是从 0 到 rowNumber 的行索引,rowNumber 是行数。

                  对于中心三角形:它看起来像“直角三角形”加上根据行索引添加 \* (例如:在第一行中您将不添加任何内容,因为索引为 0 ,在第二行中您将添加一个'*'等)。

                  【讨论】:

                    【解决方案9】:

                    对于三角形来说,你需要用三个循环代替两个循环, 一个外循环迭代行号 主循环内的两个并行循环 第一个循环打印减少循环数 第二个循环打印增加的 '' 好吧,我也可以给出确切的逻辑,但是如果您先尝试会更好 只需集中每行需要多少个空格和多少个'' 将符号数与循环迭代行数联系起来 你完成了 .....如果更麻烦,请告诉我,我会用逻辑和代码解释

                    【讨论】:

                      【解决方案10】:

                      这将以三角形打印星星:

                      `   
                      public class printstar{
                      public static void main (String args[]){
                      int m = 0;
                      for(int i=1;i<=4;i++){
                      for(int j=1;j<=4-i;j++){
                      System.out.print("");}
                      
                      for (int n=0;n<=i+m;n++){
                      if (n%2==0){
                      System.out.print("*");}
                      else {System.out.print(" ");}
                      }
                      m = m+1;
                      System.out.println("");
                      }
                      }
                      }'
                      

                      阅读和理解这将有助于您下次设计逻辑..

                      【讨论】:

                        【解决方案11】:
                        import java.util.Scanner;
                        
                        public class A {
                        
                            public void triagle_center(int max){//max means maximum star having
                                int n=max/2;
                                for(int m=0;m<((2*n)-1);m++){//for upper star
                                    System.out.print(" ");
                                }
                                System.out.println("*");
                        
                                for(int j=1;j<=n;j++){
                                    for(int i=1;i<=n-j; i++){
                                        System.out.print("  ");
                                    }
                                    for(int k=1;k<=2*j;k++){
                                    System.out.print("* ");
                                    }
                        
                                    System.out.println();
                                }
                        
                        
                            }
                        
                            public void triagle_right(int max){
                                for(int j=1;j<=max;j++){
                                    for(int i=1;i<=j; i++){
                                        System.out.print("* ");
                                    }
                        
                                    System.out.println();
                                }
                            }
                        
                            public void triagle_left(int max){
                                for(int j=1;j<=max;j++){
                                    for(int i=1;i<=max-j; i++){
                                        System.out.print("  ");
                                    }
                                    for(int k=1;k<=j; k++){
                                        System.out.print("* ");
                                    }
                        
                                    System.out.println();
                                }
                            }
                        
                            public static void main(String args[]){
                                A a=new A();
                                Scanner input = new Scanner (System.in);
                                System.out.println("Types of Triangles");
                                System.out.println("\t1. Left");
                                System.out.println("\t2. Right");
                                System.out.println("\t3. Center");
                                System.out.print("Enter a number: ");
                                int menu = input.nextInt();
                                Scanner input1 = new Scanner (System.in);
                                System.out.print("maximum Stars in last row: ");
                                int row = input1.nextInt();
                                if (menu == 1)
                                    a.triagle_left(row);
                                if (menu == 2)
                                    a.triagle_right(row);
                                if (menu == 3)
                                    a.triagle_center(row);
                            }
                        }
                        

                        【讨论】:

                          【解决方案12】:
                          public static void main(String[] args) {
                          
                              System.out.print("Enter the number: ");
                              Scanner userInput = new Scanner(System.in);
                              int myNum = userInput.nextInt();
                              userInput.close();
                          
                              System.out.println("Centered Triange");
                              for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
                          
                                  for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
                                      System.out.print(" ");
                                  }
                          
                                  for (int j = 0; j < i; j++) { //Prints a " " followed by '*'.   
                                      System.out.print(" *");
                                  }
                          
                                  System.out.println(""); //Next Line     
                              }
                          
                              System.out.println("Left Triange");
                              for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
                          
                                  for (int j = 0; j < i; j++) { //Prints the '*' first in each line then spaces.  
                                      System.out.print("* ");
                                  }
                          
                                  System.out.println(""); //Next Line         
                              }
                          
                              System.out.println("Right Triange");
                              for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
                          
                                  for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
                                      System.out.print("  ");
                                  }
                          
                                  for (int j = 0; j < i; j+=1) { //Prints the " " first in each line then a "*".  
                                      System.out.print(" *");
                                  }
                          
                                  System.out.println(""); //Next Line         
                              }
                          
                          }
                          

                          【讨论】:

                            【解决方案13】:

                            这是最简单的程序,只需要 1 个 for 循环来打印三角形。这仅适用于中心三角形,但小的调整也会使其适用于其他三角形 -

                            import java.io.DataInputStream;
                            
                            public class Triangle {
                                public static void main(String a[]) throws Exception{
                                    DataInputStream in = new DataInputStream(System.in);
                            
                                    int n = Integer.parseInt(in.readLine());
                                    String b = new String(new char[n]).replaceAll("\0", " ");
                                    String s = "*";
                                    for(int i=1; i<=n; i++){
                                        System.out.print(b);
                                        System.out.println(s);
                                        s += "**";
                                        b = b.substring(0, n-i);
                                        System.out.println();
                                    }
                                }
                            }
                            

                            【讨论】:

                              【解决方案14】:

                              对于左对齐的直角三角形,您可以在 java 中尝试以下简单代码:

                              import java.io.*;
                              import java.util.*;
                              
                              public class Solution {
                              
                                  public static void main(String[] args) {
                                    Scanner sc=new Scanner(System.in);
                                    int size=sc.nextInt();
                                     for(int i=0;i<size;i++){
                                         for(int k=1;k<size-i;k++){
                                                 System.out.print(" ");
                                             }
                                         for(int j=size;j>=size-i;j--){
                              
                                             System.out.print("#");
                                         }
                                         System.out.println();
                                     }
                                  }
                              }
                              

                              【讨论】:

                                【解决方案15】:

                                找到以下,它将帮助您打印完整的三角形。

                                package com.raju.arrays;
                                

                                公共类 CompleteTringe {

                                public static void main(String[] args) {
                                    int nuberOfRows = 10;
                                      for(int row = 0; row<nuberOfRows;row++){
                                
                                          for(int leftspace =0;leftspace<(nuberOfRows-row);leftspace++){
                                              System.out.print(" ");
                                          }
                                          for(int star = 0;star<2*row+1;star++){
                                              System.out.print("*");
                                          }
                                          for(int rightSpace =0;rightSpace<(nuberOfRows-row);rightSpace++){
                                              System.out.print(" ");
                                          }
                                          System.out.println("");
                                      }
                                
                                }
                                

                                }

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



                                【讨论】:

                                  【解决方案16】:

                                  对于中心三角形

                                        Scanner sc = new Scanner(System.in);
                                        int n=sc.nextInt();
                                        int b=(n-1)*2;  
                                        for(int i=1;i<=n;i++){
                                        int t= i;
                                        for(int k=1;k<=b;k++){
                                        System.out.print(" ");
                                         }
                                         if(i!=1){
                                          t=i*2-1;
                                         }
                                         for(int j=1;j<=t;j++){
                                         System.out.print("*");
                                         if(j!=t){
                                         System.out.print(" ");
                                         }
                                          }
                                          System.out.println();
                                              b=b-2;  
                                          }
                                  

                                  输出:

                                              *
                                            * * *
                                  

                                  【讨论】:

                                    【解决方案17】:
                                        for(int i=1;i<=5;i++)
                                        {
                                            for(int j=5;j>=i;j--)
                                            {
                                                System.out.print(" ");
                                            }
                                            for(int j=1;j<=i;j++)
                                            {
                                                System.out.print("*");
                                            }
                                    
                                            for(int j=1;j<=i-1;j++)
                                            {
                                                System.out.print("*");
                                            }
                                            System.out.println("");
                                        }
                                    
                                     *
                                    ***
                                    



                                    【讨论】:

                                    • 请粘贴一些解释。
                                    【解决方案18】:
                                    public class Triangle {
                                        public static void main ( String arg[] ) {
                                            System.out.print("Enter Triangle Size : ");
                                            int num = 0;
                                            try {
                                                num = Integer.parseInt( read.readLine() );
                                            } catch(Exception Number) {
                                                System.out.println("Invalid Number!");
                                            }
                                            for(int i=1; i<=num; i++) {
                                                for(int j=1; j<num-(i-1); j++) {
                                                    System.out.print(" ");
                                                }
                                                for(int k=1; k<=i; k++) {
                                                    System.out.print("*");
                                                    for(int k1=1; k1<k; k1+=k) {
                                                        System.out.print("*");
                                                    }
                                                }
                                                System.out.println();
                                            }
                                        }
                                    }
                                    

                                    【讨论】:

                                      【解决方案19】:

                                      目标输出:

                                            *
                                           ***
                                          *****
                                      

                                      实施:

                                      for (int i = 5; i >= 3; i--)
                                          for (int a = 1; a <= i; a++)
                                          {   
                                              System.out.print(" ");
                                          }
                                      
                                          for (int j = 10; j/2>=i; j--)
                                          {
                                              System.out.print("*");
                                          }
                                          System.out.println("");
                                      }   
                                      

                                      【讨论】:

                                        【解决方案20】:
                                        (a)   (b)        (c)   (d)
                                        * ********** ********** *
                                        ** ********* ********* **
                                        *** ******** ******** ***
                                        **** ******* ******* ****
                                        ***** ****** ****** *****
                                        ****** ***** ***** ******
                                        ******* **** **** *******
                                        ******** *** *** ********
                                        ********* ** ** *********
                                        ********** * * **********
                                        
                                        int line;
                                        int star;
                                        System.out.println("Triangle a");
                                                for( line = 1; line <= 10; line++ )
                                                {
                                                    for( star = 1; star <= line; star++ )
                                                    {
                                        
                                                        System.out.print( "*" );
                                                    }
                                                    System.out.println();
                                                }
                                        
                                         System.out.println("Triangle b");
                                        
                                                  for( line = 1; line <= 10; line++ )
                                                {
                                                    for( star = 1; star <= 10; star++ )
                                                    {
                                        
                                                if(line<star)
                                                        System.out.print( "*" );
                                                        else
                                                          System.out.print(" ");
                                                    }
                                                    System.out.println();
                                                }
                                        
                                         System.out.println("Triangle c");
                                        
                                                  for( line = 1; line <= 10; line++ )
                                                {
                                                    for( star = 1; star <= 10; star++ )
                                                    {
                                        
                                                if(line<=star)
                                                        System.out.print( "*" );
                                                        //else
                                                         // System.out.print(" ");
                                                    }
                                                    System.out.println();
                                                }
                                        
                                         System.out.println("Triangle d");
                                        
                                                  for( line = 1; line <= 10; line++ )
                                                {
                                                    for( star = 1; star <= 10; star++ )
                                                    {
                                        
                                                if(line>10-star)
                                                        System.out.print( "*" );
                                                        else
                                                          System.out.print(" ");
                                                    }
                                                    System.out.println();
                                                }
                                        

                                        【讨论】:

                                          【解决方案21】:

                                          你可能也对这个感兴趣

                                                Scanner sc = new Scanner(System.in);
                                                int n=sc.nextInt();
                                                int b=0;
                                                for(int i=n;i>=1;i--){
                                                if(i!=n){
                                                for(int k=1;k<=b;k++){
                                                System.out.print(" ");
                                                  }
                                                      }
                                                 for(int j=i;j>=1;j--){
                                                 System.out.print("*");
                                                 if(i!=1){
                                                 System.out.print(" ");
                                                  }
                                                      }
                                                 System.out.println();
                                                 b=b+2;
                                                  }
                                          

                                          输出:: 5

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

                                          【讨论】:

                                          • 你好 RKP。感谢您提供答案。请修复您的代码缩进,因为它无法按原样阅读。还请正确格式化您将来发布的代码。谢谢
                                          猜你喜欢
                                          • 1970-01-01
                                          • 1970-01-01
                                          • 1970-01-01
                                          • 1970-01-01
                                          • 1970-01-01
                                          • 1970-01-01
                                          • 2020-10-03
                                          • 1970-01-01
                                          • 1970-01-01
                                          相关资源
                                          最近更新 更多