Java 程序打印左三角星形图案

javaobject oriented programmingprogramming更新于 2024/4/15 23:08:17

在本文中,我们将了解如何打印左三角星形图案。该图案由多个 for 循环和打印语句形成。

下面是相同的演示 −

输入

假设我们的输入是 −

输入行数:8

输出

所需的输出将是 −

右三角星形图案:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *

算法

步骤 1 - 开始
步骤 2 - 声明三个整数值,即 i、j 和 my_input
步骤 3 - 从用户处读取所需值/定义值
步骤 4 - 我们迭代两个嵌套的 'for' 循环以获取字符之间的空格。
步骤 5 - 迭代最内层循环后,我们迭代另一个 'for' 循环。这将有助于打印所需的字符。
步骤 6 - 现在,打印换行符以获取后续行中的特定字符数。
步骤 7 - 显示结果
步骤 8 - 停止

示例 1

import java.util.Scanner;
public class RightTriangle{
   public static void main(String args[]){
      int i, j, my_input;
      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 number of rows : ");
      my_input = my_scanner.nextInt();
      System.out.println("The right triangle star pattern : ");
     for (i=0; i<my_input; i++){
        for (j=2*(my_input-i); j>=0; j--){
           System.out.print(" ");
        }
        for (j=0; j<=i; j++ ){
           System.out.print("* ");
        }
        System.out.println();
     }
   }
}

输出

Required packages have been imported
A reader object has been defined
Enter the number of rows : 8
The right triangle star pattern :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *

示例 2

这里,整数已经被预先定义,并且它的值被访问并显示在控制台上。

public class RightTriangle{
   public static void main(String args[]){
      int i, j, my_input;
      my_input = 8;
      System.out.println("The number of rows is defined as " +my_input);
      System.out.println("The right triangle star pattern : ");
      for (i=0; i<my_input; i++){
         for (j=2*(my_input-i); j>=0; j--){
            System.out.print(" ");
         }
         for (j=0; j<=i; j++ ){
            System.out.print("* ");
         }
         System.out.println();
      }
   }
}

输出

The number of rows is defined as 8
The right triangle star pattern :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *

相关文章


有用资源