在此Java模式程序中,我们展示了使用for循环、while循环和函数打印字母X图案的步骤。下面的程序接受用户输入的行数,并使用嵌套的for循环遍历行和列。接下来,If else语句帮助以X图案打印字母。
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 Numbers of Rows = ");
int rows = sc.nextInt();
int a = 65;
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%c", a + j);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
Enter Numbers of Rows = 11
A K
B J
C I
D H
E G
F
E G
D H
C I
B J
A K
在此程序中,我们将for循环替换为while循环来遍历X的行和列,并以X形图案打印字母。有关更多字母图案,请点击此处。
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, a = 65;
System.out.print("Enter Numbers of Rows = ");
rows = sc.nextInt();
i = 0 ;
while (i < rows )
{
j = 0 ;
while (j < rows )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%c", a + j);
}
else
{
System.out.printf(" ");
}
j++;
}
System.out.println();
i++;
}
}
}
Enter Numbers of Rows = 15
A O
B N
C M
D L
E K
F J
G I
H
G I
F J
E K
D L
C M
B N
A O
在此Java模式程序中,我们创建了一个XPatternofAlpha函数来打印用户给定行数、用字母填充的X形或图案。
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 Numbers of Rows = ");
int rows = sc.nextInt();
XPatternofAlpha(rows);
}
public static void XPatternofAlpha(int rows)
{
int a = 65;
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%c", a + j);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
