Java 程序:打印左箭头星形图案
原文:https://www.studytonight.com/java-programs/java-program-to-print-the-left-arrow-star-pattern
在本教程中,我们将看到如何在 Java 中打印左箭头星形模式。首先,我们将要求用户初始化行数。然后,我们将使用循环来打印图案。但是在继续之前,如果你不熟悉 java 中循环的概念,那么一定要查看关于 Java 中循环的文章。
输入:输入行数:6
输出:模式为:
程序 1:打印左箭头星形图案
在这个程序中,我们将看到如何使用 for 循环在 Java 中打印左箭头星形模式。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明变量来存储行数和模式符号。
- 要求用户初始化这些变量。
- 使用两个循环来打印图案。
- 第一个 for 循环显示上方的“左箭头”图案,第二个 for 循环显示下方的图案。
- 首先,检查循环的条件 i
- 第一个内部 for 循环显示空间和第二个内部 for 循环显示我们给定要显示的字符。
- 在执行第一个外部 for 循环之后,将执行第二个外部 for 循环。
- 检查循环的条件,如果为真,则执行内部循环,直到条件 i
- 显示结果。
- 停止
下面的例子说明了上述算法的实现。
//Java Program to Print the Left Arrow Star 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();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i;j++)
{
System.out.print(" ");
}
for(int j=i;j<=n;j++)
{
System.out.print("*");
}
System.out.println();
}
for(int i=1;i<n;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(" ");
}
for(int j=0;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
输入行数:6
- *
- *
程序 2:打印左箭头星形图案
在这个程序中,我们将看到如何使用 while 循环在 Java 中打印左箭头星形模式。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明变量来存储行数和模式符号。
- 要求用户初始化这些变量。
- 使用两个 while 循环来打印图案。
- 首先,在 while 处检查条件 i<=n,如果为真,则在 while 循环中执行代码。
- 第一个 while 将执行,直到 i<=n 为假。
- 在执行第一个 while 循环后,将执行第二个 while 循环。
- 显示结果。
- 停止
下面的例子说明了上述算法的实现。
//Java Program to Print the Left Arrow Star 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();
int i=1;
int j;
while(i<=n)
{
j=1;
while(j<=n-i)
{
System.out.print(" ");
j++;
}
j=i;
while(j<=n)
{
System.out.print("*");
j++;
}
System.out.println();
i++;
}
i=1;
while(i<n)
{
j=0;
while(j<i)
{
System.out.print(" ");
j++;
}
j=0;
while(j<=i)
{
System.out.print("*");
j++;
}
System.out.println();
i++;
}
}
}
输入行数:6
- *
- *
程序 3:打印左箭头星形图案
在这个程序中,我们将看到如何使用 do-while 循环在 Java 中打印左箭头星形模式。
算法:
- 开始
- 创建 Scanner 类的实例。
- 声明变量来存储行数和模式符号。
- 要求用户初始化这些变量。
- 使用两个边做边循环来打印图案。
- 首先,将执行 do-while 循环,直到条件为假 i<=n。将执行内部 do-while 循环,直到条件为假。
- 在执行第一个 do-while 循环之后,将执行第二个 do-while 循环,直到条件 i
- 显示结果。
- 停止
下面的例子说明了上述算法的实现。
//Java Program to Print the Left Arrow Star 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();
int i=1;
int j;
do
{
j=1;
do
{
System.out.print(" ");
}while(j++<=n-i);
j=i;
do
{
System.out.print("*");
j++;
}while(j<=n);
System.out.println();
i++;
} while(i<=n);
i=1;
do
{
j=0;
do
{
System.out.print(" ");
}while(j++<i);
j=0;
do
{
System.out.print("*");
j++;
} while(j<=i);
System.out.println();
i++;
}while(i<n);
}
}
输入行数:6
- *
- *