在此Java模式程序中,我们展示了如何使用for循环、while循环和函数打印字母G形状或图案的星号。
import java.util.Scanner;
public class Example
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
System.out.print("Enter Rows = ");
int rows = sc.nextInt();
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < 2 * rows; j++ )
{
if ((i == 0 || i == rows - 1) && (j == 0 || j == (2 * rows) - 2))
{
System.out.printf(" ");
}
else if ((j == 0) || (i == 0 && j <= rows) || (i == rows / 2 && j > rows / 2)
|| (i > rows / 2 && j == (2 * rows) - 1) || (i == rows - 1 && j < 2 * rows))
{
System.out.printf("*");
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
Enter Rows = 15
***************
*
*
*
*
*
*
* **********************
* *
* *
* *
* *
* *
* *
*************************** *
在此字母G形状或图案程序中,我们用while循环替换了for循环来打印每个位置的星号。有关更多字母图案和星形图案程序,请使用超链接。
import java.util.Scanner;
public class Example
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
int rows, i, j;
System.out.print("Enter Rows = ");
rows = sc.nextInt();
i = 0 ;
while ( i < rows )
{
j = 0 ;
while ( j < (2 * rows) - 1)
{
if ((i == 0 || i == rows - 1) && (j == 0 || j == (2 * rows) - 3))
{
System.out.printf(" ");
}
else if ((j == 0) || (i == 0 && j <= rows) || (i == rows / 2 && j > rows / 2)
|| (i > rows / 2 && j == (2 * rows) - 3) || (i == rows - 1 && j < (2 * rows)- 2))
{
System.out.printf("*");
}
else
{
System.out.printf(" ");
}
j++;
}
System.out.println();
i++;
}
}
}
Enter Rows = 11
***********
*
*
*
*
* ***************
* *
* *
* *
* *
******************
在此程序中,我们创建了一个AlphabetGShape函数,用于在行和列中打印由星号填充的字母G图案或形状。
import java.util.Scanner;
public class Example
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
System.out.print("Enter Rows = ");
int rows = sc.nextInt();
System.out.print("Enter Character = ");
char a = sc.next().charAt(0);
AlphabetGShape(rows, a);
}
public static void AlphabetGShape(int rows, char a)
{
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < 2 * rows; j++ )
{
if ((i == 0 || i == rows - 1) && (j == 0 || j == (2 * rows) - 2))
{
System.out.printf(" ");
}
else if ((j == 0) || (i == 0 && j <= rows) || (i == rows / 2 && j > rows / 2)
|| (i > rows / 2 && j == (2 * rows) - 1) || (i == rows - 1 && j < 2 * rows))
{
System.out.printf("%c", a);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
