在这个 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 || i + j == rows - 1)
{
if (i + j == rows - 1)
{
System.out.printf("/");
}
else
{
System.out.printf("\\");
}
}
else
{
System.out.printf("%d", i);
}
}
System.out.println();
}
}
}
Enter Numbers of Rows = 10
\00000000/
1\111111/1
22\2222/22
333\33/333
4444\/4444
5555/\5555
666/66\666
77/7777\77
8/888888\8
/99999999\
在此程序中,我们用 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();
for (i = 0 ; i < rows; i++ )
{
for (j = 0 ; j < rows; j++ )
{
if (i == j || i + j == rows - 1)
{
if (i + j == rows - 1)
{
System.out.printf("/");
}
else
{
System.out.printf("\\");
}
}
else
{
System.out.printf("%d", i);
}
}
System.out.println();
}
}
}
Enter Numbers of Rows = 8
\000000/
1\1111/1
22\22/22
333\/333
444/\444
55/55\55
6/6666\6
/777777\
在这个 Java 模式程序中,我们创建了 XinRectangleNumbers 函数来在矩形数字图案中打印 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();
XinRectangleNumbers(rows);
}
public static void XinRectangleNumbers(int rows)
{
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || i + j == rows - 1)
{
if (i + j == rows - 1)
{
System.out.printf("/");
}
else
{
System.out.printf("\\");
}
}
else
{
System.out.printf("%d", i);
}
}
System.out.println();
}
}
}
