【发布时间】:2019-08-01 19:33:40
【问题描述】:
所以,我得到了一个 .txt 文件,其中包含两个 3x3 矩阵,需要携带这些矩阵来进行加法、乘法、减法和标量乘法,其中程序只需要一个矩阵,用户将输入操作的编号。
问题是让程序只读取矩阵。
这是我得到的 .txt 文件,其中前两个数字是大小:
3 3
12 34 45
34 -12 56
76 12 -1
@
3 3
8 13 45
67 0 12
12 -12 3
那里有救生员吗?
编辑1
这是我到目前为止所拥有的,当我让用户输入矩阵时乘法方法正在工作,但现在只是给出了一些奇怪的答案,我错过了什么?
import java.io.*;
public class ReadingTest {
public static void main(String[] args) throws IOException {
BufferedReader reader;
reader = new BufferedReader(new FileReader("matrix2.txt"));
String firstDimension = reader.readLine();
String[] split = firstDimension.split(" ");
int firstX = Integer.parseInt(split[0]);
int firstY = Integer.parseInt(split[0]);
int[][] first = new int[firstX][firstY];
for (int i = 0; i < firstX; i++) {
String[] line;
line = reader.readLine().split(" ");
for (int j = 0; j < firstY; j++) {
first[i][j] = Integer.parseInt(line[j]);
}
}
// Read "@"
reader.readLine();
String secondDimension = reader.readLine();
String[] split2 = secondDimension.split("");
int secX = Integer.parseInt(split2[0]);
int secY = Integer.parseInt(split2[0]);
int[][] second = new int[secX][secY];
for (int i = 0; i < secX; i++) {
String[] line;
line = reader.readLine().split(" ");
for (int j = 0; j < secY; j++) {
second[i][j] = Integer.parseInt(line[j]);
}
}
// System.out.println(Arrays.deepToString(second));
multiply(first, second);
reader.close();
}
public static void multiply(int[][] first, int[][] second) {
for (int i = 0; i < first.length; i++) {
int total = 0;
for (int j = 0; j < second[0].length; j++) {
int fnum = first[i][j];
int snum = second[j][i];
int product = fnum * snum;
total += product;
}
System.out.print(total + " ");
}
}
}
【问题讨论】:
-
到目前为止你尝试过什么?为什么它不起作用 - 您得到什么结果以及预期结果是什么?
-
我让用户输入矩阵,但后来发现我必须使用这个文本文件。不知道如何使用扫描仪只读取矩阵而忽略其余部分
-
嗨 Nicloas,欢迎来到 SO
-
所以基本上你自己什么都没试过,希望我们为你解决问题?网上有很多教程展示了如何在 java 中读取文本文件。
标签: java arrays matrix matrix-multiplication