java - 创建方阵

标签 java matrix

你好,有人可以帮我吗,我正在尝试用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/

相关文章:

java - 如何从 Neo4j 中的 Node 属性获取实际字符串

java - Firebase 引用对象无法解析为类型

sql - 使用查找矩阵中最接近的值更新表

c - C 中的矩阵排序

java - 未添加 maven 程序集传递依赖项

java - 从 Jboss-as 7.1.1 中的 standalone.xml 外部化资源适配器配置

java - 在 tomcat 中关闭浏览器进行 websocket 连接刷新时,tomcat 控制台中抛出错误

matlab - 同时删除矩阵中的一行和一列

matrix - Julia:如何在另一个矩阵的特定行中插入特定行的矩阵

Python 数组索引开关 - 发生了什么?