java - 打印方阵并使用 Java 对其进行转置

标签 java matrix transpose square

我需要编写一个程序,从用户那里获取数字 n 并创建一个向上计数的 nxn 矩阵,然后我需要转置它。我尝试了多种编码方法,但没有任何显示正确。

import java.util.Scanner;

public class SquareMatrix {
  public static void main(String[] args)
{
    //Variables
    int size;
    int value;

    //Scanner
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);

    //Prompt
    System.out.println("Enter the size of the Square Matrix: ");
    size = input.nextInt();


    for(int i=1; i<=size; i++) {
        System.out.println();

        for(int j=0; j<size; j++) {

            value = i+j;
            System.out.print(value);

        }
     }

  }

}

我目前得到的结果是:

Enter the size of the Square Matrix: 
3

123
234
345

我需要它看起来更像这样:

Enter the Size of the Square Matrix:
3
Square Matrix:
1 2 3 
4 5 6 
7 8 9 
Transpose:
1 4 7 
2 5 8 
3 6 9 

最佳答案

nxn矩阵向上计数为

    for(int i=0; i<size; i++) {
        System.out.println();

        for(int j=1; j<=size; j++) {

            value = j + i*size;
            System.out.print(value);

        }
     }

转座是

  for(int i=1; i<=size; i++) {
        System.out.println();

        for(int j=0; j<size; j++) {

            value = j*size + i;
            System.out.print(value);

        }
     }

关于java - 打印方阵并使用 Java 对其进行转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28863881/

相关文章:

java - 是否有针对错误的 Java 注释?

java - 如何实现打印下一个较小元素的索引的方法(在java中)?

r - 矩阵到具有行/列数的数据框

arrays - 从冗余索引列表更新矩阵

r - 来自 R "image"函数的意外转置翻转输出

apache-spark - PySpark:如何转置数据帧中的多列

python - 无法转置 dask.dataframe - 获取未绑定(bind)本地错误

java - 使用 Binder.transact() 时发生 NullPointerException?

java - JSTL中计算的jsp中访问JSTL变量

matlab - 复制向量并将每个副本向下移动 1 行,无需 for 循环