【发布时间】:2021-01-12 00:17:37
【问题描述】:
谁能告诉我为什么矩阵加法在这段代码中不起作用?该程序的所有其他部分都在工作,除了添加部分。它只是打印一个空数组作为输出。
import java.util.*;
class matrix{
int n1, n2 = 0;
int[][] matrix1 = new int [n1][n2];
int[][] matrix2 = new int [n1][n2];
int[][] matrix3 = new int [n1][n2];
Scanner sc = new Scanner(System.in);
// get the dimensions of the matrix//
void Matrix() {
int n1, n2 = 0;
System.out.println(" enter the dimension of the matrix");
n1 = sc.nextInt();
n2 = sc.nextInt();
int[][] matrix1 = new int [n1][n2];
int[][] matrix2 = new int [n1][n2];
//get the values of the elements//
System.out.println("Enter the elements of the matrix");
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
matrix1[i][j] = sc.nextInt();
matrix2[i][j] = matrix1[i][j];
}
}
// print the arrays
System.out.println("matrix1"+Arrays.deepToString(matrix1));
System.out.println("matrix2"+Arrays.deepToString(matrix2));
}
void add() {
int[][] matrix3 = new int[n1][n2];
for (int i = 0; i < n1; i++) {
for(int j=0; j < n2; j++) {
matrix3[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
System.out.println("Addition of the elements" + Arrays.deepToString(matrix3));
}
}
public class arrays2 {
public static void main(String[] args) {
matrix M1 = new matrix();
M1.Matrix();
M1.add();
}
}
【问题讨论】:
-
因为在方法
Matrix()的范围内有局部矩阵matrix1、matrix2。您不需要在方法中重新声明它们,只需分配即可。
标签: java arrays function matrix methods