Java程序打印空心直角三角形星号图案


在这篇文章中,我们将学习如何打印空心直角三角形星号图案。该图案是通过使用多个for循环和print语句形成的。第一行金字塔将打印一颗星,最后一行将打印n颗星。其他行将在行的开头和结尾处打印正好两颗星,这两颗星之间将有一些空格。

以下是相同的演示 -

输入

假设我们的输入是 -

Enter the size : 8

输出

期望的输出将是 -

The hollow pyramid triangle :
*
* *
*  *
*   *
*    *
*     *
********

算法

Step 1 - START
Step 2 - Declare four integer values namely i, j, k and my_input.
Step 3 - Read the required values from the user/ define the values
Step 4 - We iterate through two nested 'for' loops to get space between the characters.
Step 5 - After iterating through the innermost loop, we iterate through another 'for' loop. This will help print the required character.
Step 6 - Now, print a newline to get the specific number of characters in the subsequent lines.
Step 7 - Display the result
Step 8 - Stop

示例1

这里,输入是根据提示由用户输入的。您可以在我们的代码练习工具 运行按钮中实时尝试此示例。

import java.util.Scanner;
public class Hollowtangle{
   public static void main(String[] args){
      int my_input, k, i, j;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the size : ");
      my_input = my_scanner.nextInt();
      for( i=1;i<=my_input;i++){
         if(i==1 || i==my_input)
         for( j=1;j<=i;j++){
            System.out.print("*");
         } else {
             for( j=1;j<=i;j++){
                if(j==1 || j==i)
                   System.out.print("*");
                else
                   System.out.print(" ");
            }
         }
      System.out.println();
      }
   }
}

输出

Required packages have been imported
A reader object has been defined
Enter the size : 8
**
* *
*  *
*   *
*    *
*     *
********

示例2

这里,整数已预先定义,其值在控制台中被访问和显示。

public class Hollowtangle{
   public static void main(String[] args){
      int my_input, i, j;
      my_input = 8;
      System.out.println("The size is defined as " +my_input);
      for( i=1;i<=my_input;i++){
         if(i==1 || i==my_input)
         for( j=1;j<=i;j++){
            System.out.print("*");
         } else {
            for( j=1;j<=i;j++){
               if(j==1 || j==i)
                  System.out.print("*");
               else
                  System.out.print(" ");
            }
         }
         System.out.println();
      }
   }
}

输出

The size is defined as 8
*
**
* *
*  *
*   *
*    *
*     *
********

更新于:2022年2月25日

4K+浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.