你好,有人可以帮我吗,我正在尝试用java用这种格式做一个方阵:
1 | 6 | 7 | 12
2 | 5 | 8 | 11
3 | 4 | 9 | 10
我想要的是代码生成一个具有用户指定大小的表格,并按照上面给定的格式打印它。
我以为我已经完成了它,但是当我输入奇数作为列时,它总是会添加另一列。因此,例如,
**输入:**我输入了3
作为编号。列数
,
**输出:**它将打印四 (4
) 列。
这是我的代码(用java编写):
System.out.print("Enter Number(s) of ROW: ");
int numRow = in.nextInt();
System.out.print("Enter Number(s) of COLUMN: ");
int numCol = in.nextInt();
int [][] Table = new int[numRow][numCol];
int ctr=0;
for(int row=0; row<numRow; row++)
{
for(int col=0; col<numCol; col++)
{
Table[row][col]= (col*numRow)+row+1;
System.out.print(Table[row][col]+"\t");
for(int i=col+1; i<=numRow; i++)
{
ctr=(numRow-1)-row;
Table[row][col]= (i*numRow)+ctr+1;
System.out.print(Table[row][col]+"\t");
i=numRow;
}
col++;
}
System.out.println();
}
最佳答案
使用此代码:
import java.util.Scanner;
public class Teas {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Number(s) of ROW: ");
int numRow = in.nextInt();
System.out.print("Enter Number(s) of COLUMN: ");
int numCol = in.nextInt();
int [][] Table = new int[numRow][numCol];
int ctr=0;
for(int row=0; row<numRow; row++)
{
for(int col=0; col<numCol; col++)
{
if(col%2 == 0){Table[row][col] = (col * numRow +1 )+ row;}
else{Table[row][col] = (numRow * (col + 1))- row;}
}
}
for(int row=0; row<numRow; row++)
{
for(int col=0; col<numCol; col++)
{
System.out.print(Table[row][col] +"|");
}
System.out.println("");
}
}
}
关于java - 创建方阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56767138/