2019-09-28 15:48

# 初学Java，矩阵相乘，输入两个二维数组时遇到问题，求解答，谢谢！

2 3

1 2 3

4 5 6

3 2

7 8

9 0

1 2

``````import java.util.Scanner;

public class Matrix {
int matrix[][];
int row;
int colunmn;
Scanner input = new Scanner(System.in);

Matrix() {
row = 0;
colunmn = 0;
}

Matrix muti(Matrix m) {
input.close();
Matrix result = new Matrix();

result.row = row;
result.colunmn = m.colunmn;
result.matrix = new int[result.row][result.colunmn];

for (int i = 0; i < result.row; i++) {
for (int j = 0; j < result.colunmn; j++) {
for (int k = 0; k < m.row; k++) {
result.matrix[i][j] += matrix[i][k] * m.matrix[k][j];
}
}
}
return result;
}

int get_row() {
return row;
}

int get_column() {
return colunmn;
}

void set_row_column() {

row = input.nextInt();
colunmn = input.nextInt();
}

void set_matrix() {

matrix = new int[row][colunmn];

for (int i = 0; i < row; i++) {
for (int j = 0; j < colunmn; j++) {
matrix[i][j] =  input.nextInt();
}
}
}

void show_matrix()
{
for (int i = 0; i < row; i++) {
for (int j = 0; j < colunmn; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

``````

``````public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
Matrix m1 = new Matrix();
Matrix m2 = new Matrix();
Matrix result = new Matrix();

m1.set_row_column();
m1.set_matrix();
m2.set_row_column();
m2.set_matrix();
result = m1.muti(m2);
result.show_matrix();
}

}
``````
• 写回答
• 好问题 提建议
• 追加酬金
• 关注问题
• 邀请回答