编写一个 Java 程序,使用 for 循环打印方阵行和列的相同数字模式。
import java.util.Scanner;
public class sameNuminSquareRC1 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Enter Square Side = ");
int rows = sc.nextInt();
System.out.println("Printing Same Numbers in Rows & Columns of a Square");
for (int i = 1 ; i <= rows; i++ )
{
for (int j = i ; j < rows + 1; j++ )
{
System.out.print(j + " ");
}
for(int k = 1; k < i; k++)
{
System.out.print(k + " ");
}
System.out.println();
}
}
}

此 Java 示例使用 while 循环显示行和列具有相同数字的方阵模式。
import java.util.Scanner;
public class sameNuminSquareRC2 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Enter Square Side = ");
int rows = sc.nextInt();
System.out.println("Printing Same Numbers in Rows & Columns of a Square");
int i = 1, j, k;
while ( i <= rows)
{
j = i;
while( j < rows + 1 )
{
System.out.print(j + " ");
j++;
}
k = 1;
while( k < i)
{
System.out.print(k + " ");
k++;
}
System.out.println();
i++;
}
}
}
Enter Square Side = 9
Printing Same Numbers in Rows & Columns of a Square
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8