如何将包含矩阵的文件读取为向量的向量?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将包含矩阵的文件读取为向量的向量?相关的知识,希望对你有一定的参考价值。
我有一个包含以下格式数据的文件:
5
11 24 07 20 03
04 12 25 08 16
17 05 13 21 09
10 18 01 14 22
23 06 19 02 15
3
04 09 02
03 05 07
08 01 06
第一个数字表示方矩阵的大小,该数字之后的线是矩阵中用空格分隔的元素。
如何将这些数据读入向量向量?抱歉,我是编程新手。我如何确保一旦程序获得大小,它便会读取矩阵的确切行数?会有很多矩阵,因此,在将值传递给适当的函数后,如何清除向量?
我认为我所做的代码对您没有任何意义,但这是...
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Vector;
public class Main
{
public static void main(String[] args) throws Exception
{
FileInputStream fstream = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Vector<Vector<Integer>> matrix = new Vector<Vector<Integer>>();
Vector<Integer> rows = new Vector<Integer>();
Vector<Integer> columns = new Vector<Integer>();
String line;
int size;
while((line = br.readLine()) != null)
{
String[] temp = line.split(" ");
for(String element: temp)
{
/* This is what I was thinking:
If element is the only thing in the line then make it size.
Once you have the size, enter the data into vectors.
I don't know how to code these parts especially how can you put the
elements in vector of vectors. Like how can I store them in rows and
columns? Arrays is simple because you can say store at arr[1][2].
*/
size = Integer.parseInt(element);
rows.add(Integer.parseInt(element));
}
}
}
}
答案
关于您的代码的评论:
您应使用try-with-resources。
删除
DataInputStream
。您甚至没有使用添加的内容。不要使用
Vector
,请改用List
。或建立一个int[][]
,因为您知道大小。不要在循环前声明
rows
和columns
。
这里是可能的代码示例:
try (BufferedReader br = Files.newBufferedReader(Paths.get("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
int size = Integer.parseInt(line);
List<List<Integer>> matrix = new ArrayList<>();
for (int i = 0; i < size; i++) {
if ((line = br.readLine()) == null)
throw new EOFException();
List<Integer> row = new ArrayList<>();
for (String value : line.split(" "))
row.add(Integer.parseInt(value));
matrix.add(row);
}
System.out.println(matrix);
}
}
输出
[[11, 24, 7, 20, 3], [4, 12, 25, 8, 16], [17, 5, 13, 21, 9], [10, 18, 1, 14, 22], [23, 6, 19, 2, 15]]
[[4, 9, 2], [3, 5, 7], [8, 1, 6]]
如前所述,您也可以构建2D数组:
try (BufferedReader br = Files.newBufferedReader(Paths.get("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
int size = Integer.parseInt(line);
int[][] matrix = new int[size][size];
for (int i = 0; i < size; i++) {
if ((line = br.readLine()) == null)
throw new EOFException();
String[] values = line.split(" ");
for (int j = 0; j < size; j++)
matrix[i][j] = Integer.parseInt(values[j]);
}
System.out.println(Arrays.deepToString(matrix));
}
}
以上是关于如何将包含矩阵的文件读取为向量的向量?的主要内容,如果未能解决你的问题,请参考以下文章