我有一个包含以下格式数据的文件:
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
第一个数字表示方阵的大小,该数字后面的行是由空格分隔的矩阵元素。
如何将此数据读入 vector vector ?抱歉,我是编程新手。如何确保程序获得大小后,它会读取矩阵的确切行数?会有很多矩阵,那么在将值传递给适当的函数后如何清除 vector ?
我认为我所做的代码对您来说没有任何意义,但它是......
File file = new File("magic.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine())
{
String line = sc.nextLine();
String[] lineArr = line.split(" ");
int[] elements = new int[lineArr.length];
int size = sc.nextInt();
Vector<Vector<Integer>> matrix = new Vector<>(size);
Vector<Integer> row = new Vector<>(size);
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
row.add(j, elements[i]);
}
matrix.add(i, row);
}
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
System.out.println(matrix.get(i).get(j));
}
System.out.println();
}
}
最佳答案
关于您的代码的评论:
您应该使用 try-with-resources。
删除
DataInputStream
。您甚至没有使用添加的内容。不要使用
Vector
,而使用List
。或者构建一个int[][]
,因为您知道大小。不要在循环之前声明
行
和列
。
以下是代码示例:
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));
}
}
关于java - 如何将包含矩阵的文件读取为 vector 的 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58478583/