【发布时间】:2017-06-07 11:03:37
【问题描述】:
好的,程序的目标是将两个由文件填充的矩阵相加。我的程序可以很好地创建和打印第一个数组,但是当我尝试填充和打印第二个数组时,它只会填充并重新打印第一个数组。我可以证明原因,但我不确定如何解决它。
这是文件
3 4
2 1 7 -10
0 5 -3 12
1 7 -2 -5
0 1 2 3
4 5 6 7
8 9 0 1
3 和 4 只是用于确定行和列,如下面的代码所示。所以第一个数组/矩阵是:
2 1 7 -10
0 5 -3 12
1 7 -2 -5
第二个
0 1 2 3
4 5 6 7
8 9 0 1
这是我的代码:
public class Matrices {
public static int[][] readMatrix(int rows, int columns, String file) throws FileNotFoundException {
Scanner fileReader = new Scanner(new FileInputStream(file));
rows = fileReader.nextInt();
columns = fileReader.nextInt();
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return result;
}
public static void printMatrix(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
还有我的司机:
public class MatricesDriver {
public static void main(String[] args)throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
File file = new File(filename);
int rows = 0;
int columns = 0;
int[][] a = Matrices.readMatrix(rows, columns, filename);
int[][] b = Matrices.readMatrix(rows, columns, filename);
Matrices.printMatrix(a);
System.out.println();
Matrices.printMatrix(b);
}
}
代码可以很好地填充和打印第一个矩阵,但不能在第二个矩阵上执行相同的操作。这是输出:
Enter name of file:
data/MAtrices.txt
2 1 7 -10
0 5 -3 12
1 7 -2 -5
2 1 7 -10
0 5 -3 12
1 7 -2 -5
它只是再次打印第一个矩阵。如何使用同一个文件创建两个单独的矩阵?
【问题讨论】:
标签: java arrays matrix netbeans