在此 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);
int rows, i, j;
System.out.print("Enter Numbers of Rows = ");
rows = sc.nextInt();
for (i = 0 ; i < rows; i++ )
{
for (j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%d", j + 1);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
Enter Numbers of Rows = 12
1 12
2 11
3 10
4 9
5 8
67
67
5 8
4 9
3 10
2 11
1 12
在此程序中,我们用while 循环替换了for 循环来遍历行和列并打印 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;
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("%d", j + 1);
}
else
{
System.out.printf(" ");
}
j++;
}
System.out.println();
i++;
}
}
}
Enter Numbers of Rows = 17
1 17
2 16
3 15
4 14
5 13
6 12
7 11
8 10
9
8 10
7 11
6 12
5 13
4 14
3 15
2 16
1 17
在此 Java 图案程序中,我们创建了一个 XNumPattern 函数来在每一行上打印 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();
XNumPattern(rows);
}
public static void XNumPattern(int rows)
{
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%d", j + 1);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
