二维数组矩阵Java代码 [英] 2 dimensional array matrix java code

查看:80
本文介绍了二维数组矩阵Java代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以为这种输出提供代码吗?用户输入等于cols的所需行数,并显示矩阵和转置矩阵.

输入行:3
输入cols:3

普通矩阵:
1 2 3
4 5 6
7 8 9

转置矩阵:
1 4 7
2 5 8
3 6 9

如果可以,可以提供代码吗?

还是尝试重写我的代码?

can anyone have the code for this kind of output? where the user enter a desired number of rows equal to cols and displays the matrix and the transposed matrix.

enter rows: 3
enter cols: 3

Normal Matrix:
1 2 3
4 5 6
7 8 9

Transposed Matrix:
1 4 7
2 5 8
3 6 9

if you do, can you give the code?

or try to rewrite the code I have?

import java.util.*;

public class transpose1 {
        public static void main(String[] args) throws Exception {
                int rows, cols;
                int[][] matrix, tmatrix;
                Scanner input = new Scanner(System.in);
                System.out.print("Enter number of rows: ");
                rows = input.nextInt();
                System.out.print("Enter number of columns: ");
                cols = input.nextInt();
                matrix = new int[rows][cols];
                tmatrix = new int[cols][rows];
                int x = rows * cols;
                for (int i = 0; i < rows; i++) {
                    for (int j = 0; j < cols; j++) {
                    }
                }
                for (int i = 0; i < rows; i++) {
                        for (int j = 0; j < cols; j++) {
                                tmatrix[i][j] = matrix[j][i];
                        }
                }
                System.out.println("Matrix is:");
                for (int i = 0; i < rows; i++) {
                        for (int j = 0; j < cols; j++) {
                                System.out.print(matrix[i][j] + " ");                        }
                        System.out.println();
                }
                System.out.println("Its transpose is: ");
                for (int i = 0; i < cols; i++) {
                        for (int j = 0; j < rows; j++) {
                                System.out.print(tmatrix[i][j] + " ");
                        }
                        System.out.println();
                }
        }
}

推荐答案

我们不提供代码.您必须使用您的代码.
无论如何:如果是您的代码或其他代码,老师将很容易理解.在公司中看到代码时,我可以轻松识别出谁写了代码.

您的代码:

-班级以大写字母命名:
We do not provide code. You''ll have to use your code.
Anyway: The teacher will figure quite easily if it''s your code or antoher ones. I can easily identify who wrote a code when I see it here in our company.

Your code:

- Classes are named with capital Letter:
public class Transpose1 {
 // code
}



-您在matrix tmatrix中的值以0开头.
要使它们充满:



- your values in matrix and tmatrix are initalized with 0.
To get them filled:

int x = 0; // start at 0
for (int i = 0; i < rows; i++) {
  for (int j = 0; j < cols; j++) {
    matrix[i][j] = x++; // increment after value set
  }
}



然后就好了.



Then it looks fine.


这篇关于二维数组矩阵Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆