在此 Java 图案程序中,我们展示了如何使用 for 循环、while 循环和函数来打印字母 K 形状或图案的星号。
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();
int n = rows / 2;
for (int i = 0; i < rows; i++)
{
System.out.printf("*");
for (int j = 0; j <= n; j++)
{
if (j == Math.abs(n - i))
{
System.out.printf("*");
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
Enter Rows = 15
* *
* *
* *
* *
* *
* *
* *
**
* *
* *
* *
* *
* *
* *
* *
在此字母 K 形状或图案 程序 中,我们用 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, n;
System.out.print("Enter Rows = ");
rows = sc.nextInt();
n = rows / 2;
i = 0 ;
while ( i < rows )
{
System.out.printf("*");
j = 0;
while ( j <= n)
{
if (j == Math.abs(n - i))
{
System.out.printf("*");
}
else
{
System.out.printf(" ");
}
j++;
}
System.out.println();
i++;
}
}
}
Enter Rows = 18
* *
* *
* *
* *
* *
* *
* *
* *
* *
**
* *
* *
* *
* *
* *
* *
* *
* *
在此程序中,我们创建了一个 AlphabetKShape 函数来打印由星号填充的字母 L 图案或形状,这些星号分布在行和列上。
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);
AlphabetKShape(rows, a);
}
public static void AlphabetKShape(int rows, char a)
{
int n = rows/ 2;
for (int i = 0; i < rows; i++)
{
System.out.printf("%c", a);
for (int j = 0; j <= n; j++)
{
if ( j == Math.abs(n - i))
{
System.out.printf("%c", a);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
