编写一个Java程序,使用for循环打印金字塔星形图案。此示例使用两个嵌套的for循环来迭代行和显示星形。
package ShapePrograms;
import java.util.Scanner;
public class PyramidPattern1 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter Pyramid Pattern Rows = ");
int rows = sc.nextInt();
System.out.println("--- Printing Pyramid Pattern of Stars ---");
for (int i = 1 ; i <= rows; i++ )
{
for (int j = 0 ; j < rows - i; j++ )
{
System.out.print(" ");
}
for (int k = 0 ; k < (i * 2) - 1; k++ )
{
System.out.print("*");
}
System.out.println();
}
}
}

在此金字塔星形图案程序中,我们将for循环替换为while循环。
package ShapePrograms;
import java.util.Scanner;
public class PyramidPattern2 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter Pyramid Pattern Rows = ");
int rows = sc.nextInt();
System.out.println("--------");
int i = 1 ;
while( i <= rows)
{
int j = 0 ;
while(j < rows - i )
{
System.out.print(" ");
j++;
}
int k = 0 ;
while(k < (i * 2) - 1)
{
System.out.print("*");
k++;
}
System.out.println();
i++;
}
}
}
Please Enter Pyramid Pattern Rows = 9
--------
*
***
*****
*******
*********
***********
*************
***************
*****************
下面显示的程序使用do-while循环打印金字塔星形图案。
package ShapePrograms;
import java.util.Scanner;
public class PyramidPattern3 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter Pyramid Pattern Rows = ");
int rows = sc.nextInt();
System.out.println("--------");
int j, k, i = 1;
do
{
j = 0;
do
{
System.out.print(" ");
}while(j++ < rows - i );
k = 0;
do
{
System.out.print("*");
}while(++k < (i * 2) - 1);
System.out.println();
}while(++i <= rows);
}
}
Please Enter Pyramid Pattern Rows = 10
--------
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
在此示例中,PyramidPattern函数打印给定符号的金字塔图案。
package ShapePrograms;
import java.util.Scanner;
public class PyramidPattern4 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter Rows = ");
int rows = sc.nextInt();
System.out.print("Please Enter Character for Pyramid Pattern = ");
char ch = sc.next().charAt(0);
System.out.println("--------");
PyramidPattern(rows, ch);
}
public static void PyramidPattern(int rows, char ch) {
for (int i = 1 ; i <= rows; i++ )
{
for (int j = 0 ; j < rows - i; j++ )
{
System.out.print(" ");
}
for (int k = 0 ; k < (i * 2) - 1; k++ )
{
System.out.print(ch);
}
System.out.println();
}
}
}
Please Enter Rows = 15
Please Enter Character for Pyramid Pattern = #
--------
#
###
#####
#######
#########
###########
#############
###############
#################
###################
#####################
#######################
#########################
###########################
#############################