Java 程序:打印镜像直角三角形图案
原文:https://www.studytonight.com/java-programs/java-program-to-print-the-mirrored-right-triangle-pattern
在本教程中,我们将看到如何在 Java 中打印镜像的直角三角形图案。首先,我们将要求用户初始化行数。然后,我们将使用循环来打印图案。但是在继续之前,如果你不熟悉 java 中循环的概念,那么一定要查看关于 Java 中循环的文章。
输入:输入行数:6
输出:模式为:
*
**
这可以通过使用以下方法来实现:
方法 1:使用 For 循环
方法 2:使用 While 循环
方法 3:使用边做边循环
让我们看看这些方法中的每一种,以便更好地理解。
程序 1:打印镜像直角三角形图案
在这个程序中,我们将看到如何使用 for 循环在 java 中打印镜像直角三角形图案。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明变量来存储行数和模式符号。
- 要求用户初始化这些变量。
- 使用 for 循环打印图案。
- 首先运行外部 for 循环,结构为(int I = 1;I < = n;i++)来遍历从 i=1 到 i=n 的行。
- 外环的条件为真,则第一个内环以(int j = 0;j < n-I;j++),如果 i<=n,则打印空格。
- 第二个内部循环使用该结构运行,如果 j
- 然后光标移动到下一行,第二次迭代开始,重复直到 i<=n。
- 显示结果。
- 停止
下面的例子说明了上述算法的实现。
//Java Program to Print the Mirrored Right Triangle Pattern
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//Take input from the user
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows: ");
int n=sc.nextInt();
System.out.println("Enter the symbol : ");
char ch = sc.next().charAt(0);
for(int i=1;i<=n;i++)
{
for(int j=0;j<n-i;j++)
{
System.out.print(" ");
}
for(int j=0;j<i;j++)
{
System.out.print(ch);
}
System.out.println();
}
}
}
输入行数:6 输入符号:
- *
程序 2:打印镜像直角三角形图案
在这个程序中,我们将看到如何使用 while 循环在 java 中打印镜像直角三角形模式。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明变量来存储行数和模式符号。
- 要求用户初始化这些变量。
- 使用 while 循环打印图案。
- 首先,检查外部 while 循环 i<=n 的条件,如果为真,则将 j 初始化为 0。
- 如果 j++
- j 值初始化为 0,第二个内部 while 循环打印字符 j
- 光标移动到下一行,I 值增加 1,再次检查外部 while 条件,重复直到外部循环的条件为假。
- 显示结果。
- 停止
下面的例子说明了上述算法的实现。
//Java Program to Print the Mirrored Right Triangle Pattern
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//Take input from the user
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows: ");
int n=sc.nextInt();
System.out.println("Enter the symbol : ");
char ch = sc.next().charAt(0);
int i=1,j;
while(i<=n)
{
j=0;
while(j++<(n-i))
{
System.out.print(" ");
}
j=0;
while(j<i)
{
System.out.print(ch);
j++;
}
System.out.println();
i++;
}
}
}
输入行数:6 输入符号:# # #
#
#
#
# # # #
程序 3:打印镜像直角三角形图案
在这个程序中,我们将看到如何使用 do-while 循环在 java 中打印镜像直角三角形模式。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明变量来存储行数和模式符号。
- 要求用户初始化这些变量。
- 使用边做边循环打印图案。
- 首先,将 j 初始化为 0。内部 do 循环打印一次空格,然后检查条件(+j
- 接下来,将 j 初始化为 0。第二个内部循环打印字符,然后检查 while 条件(j++
- 光标到达下一行,然后检查外部 do-while 循环的条件,如果(+i
- 显示结果。
- 停止
下面的例子说明了上述算法的实现。
//Java Program to Print the Mirrored Right Triangle Pattern
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//Take input from the user
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows: ");
int n=sc.nextInt();
System.out.println("Enter the symbol : ");
char ch = sc.next().charAt(0);
int i=1,j;
do
{
j=0;
do
{
System.out.print(" ");
}while(j++<(n-i));
j=0;
do
{
System.out.print(ch);
j++;
}while(j<i);
System.out.println();
i++;
}while(i<=n);
}
}
输入行数:6 输入符号:@ @ @ @ @ @ @ @ @ @ @ @ @ @ T7】