如何解决从文件Java获取矩阵
我目前有一个格式为
的文本文件matrix
row
a
b
c
row
d
e
f
row
g
h
i
row
j
k
l
matrix
row
m
n
o
p
q
row
r
s
t
u
v
我想将此格式转换为两个整数矩阵(存储为2个2D数组)
a b c
d e f
g h i
j k l
和
m n o p q
r s t u v
到目前为止,我已经创建了文件的Scanner对象,并将每一行放入文本数组:
Scanner sf = new Scanner(new File("C:\\textfiles\\matrices.txt"));
int maxIndex = -1;
String text[] = new String[10000]; // I added more than necessary for safety
while (sf.hasNext()){
maxIndex++;
text[maxIndex] = sf.nextLine();
}
sf.close();
这样,文本文件现在包含在字符串数组中,其中每一行都是该数组的新元素。现在,我想将数组划分为两个数组,每个数组都是矩阵。我应该如何继续? (注意:我是一个总的初学者,希望得到简单的答案(没有arraylist,hashmap等),这就是为什么这个问题不是How to read two matrices from a txt file in java的重复,因为它使用了BufferedReader,并且还有其他潜在的重复问题,所以我想澄清一下)
目前我排在榜首之后的是
int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];
while (counter < maxIndex){
if (counter = 0)
{
\\not yet written...
}
\\not yet written...
}
解决方法
这就是您想要的。不幸的是,使用二维数组很难做到这一点,因为一旦设置了数组的大小,就很难改变它。因此,使用ArrayList
容易得多。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static final String MATRIX = "matrix";
public static final String ROW = "row";
public static void main(String[] args) throws FileNotFoundException {
// Use correct file name here
Scanner sf = new Scanner(new File("matrices.txt"));
// This is a List of 2D Lists
List<List<List<String>>> matrices = new ArrayList<>();
// easier to process lines as we're reading them in so we
// only iterate over the file once
while (sf.hasNext()) {
boolean hasBeenProcessed = false;
String inputValue = sf.nextLine();
switch (inputValue) {
case MATRIX:
ArrayList<List<String>> matrix = new ArrayList<>();
matrices.add(matrix);
hasBeenProcessed = true;
break;
case ROW:
List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
currentMatrix.add(new ArrayList<String>());
hasBeenProcessed = true;
break;
}
if (!hasBeenProcessed) {
List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
List<String> currentRow = getCurrentRow(currentMatrix);
currentRow.add(inputValue);
}
}
// Print out the results:
int i = 1;
for (List<List<String>> matrix : matrices) {
System.out.println("Matrix " + i);
for (List<String> row : matrix) {
for (String element : row) {
System.out.print(element + " "); // no newline until end of the row
}
System.out.println(); // new line
}
i++;
System.out.println(); // new line
}
}
private static List<String> getCurrentRow(List<List<String>> currentMatrix) {
int lastRow = currentMatrix.size() - 1;
return currentMatrix.get(lastRow);
}
private static List<List<String>> getMatrixBeingProcessed(List<List<List<String>>> matrices) {
int lastMatrix = matrices.size() - 1;
List<List<String>> currentMatrix = matrices.get(lastMatrix);
return currentMatrix;
}
}
输出:
Matrix 1
a b c
d e f
g h i
j k l
Matrix 2
m n o p q
r s t u v
Process finished with exit code 0
,
正如@Rob所说的,如果没有诸如ArrayList这样的动态数据结构,这样做确实很麻烦。但是,尽管如此,这是一个可以完成您的工作的代码(考虑到您只有两个矩阵),而无需使用任何List:
int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];
int rowSize = 0,numberOfRows = 0;
counter = 2;
while (!text[counter].equals("row") && !text[counter].equals("matrix")) {
counter++;
rowSize++;
}
//now we have the row size
numberOfRows = 1;
while (!text[counter].equals("matrix")) {
if (text[counter].equals("row"))
numberOfRows++;
counter++;
}
//now we have the total number of rows
matrix1 = new int[numberOfRows][rowSize];
counter = 2; //to start from the first matrix
//now counter should point to the first row of the first matrix
while (!text[counter].equals("matrix")) {
jCounter = 0;
while (!text[counter].equals("row")
&& !text[counter].equals("matrix")) {
matrix1[iCounter][jCounter++] = Integer.parseInt(text[counter]);
//supposing your input is Integers,otherwise,you can change
//it to the corresponding type (i.e. Long,Double,etc)
counter++;
}
iCounter++;
if (!text[counter].equals("matrix"))
counter++;
}
//now we finished with the first matrix,and the counter points to
//the first "row" of the second matrix,so we do the same thing again
rowSize = 0;
numberOfRows = 0;
int startOfSecondMatrix = counter + 2; //save this for later
counter += 2; // so that counter points to the first number
while (counter < text.length && !text[counter].equals("row")) {
counter++;
rowSize++;
}
numberOfRows = 1;
while (counter < text.length) {
if (text[counter].equals("row"))
numberOfRows++;
counter++;
}
matrix2 = new int[numberOfRows][rowSize];
counter = startOfSecondMatrix;
iCounter = 0;
while (counter < text.length) {
jCounter = 0;
while (counter < text.length && !text[counter].equals("row")) {
matrix2[iCounter][jCounter++] = Integer.parseInt(text[counter]);
counter++;
}
iCounter++;
counter++;
}
对于每个矩阵,我们执行相同的操作:
-我们首先浏览矩阵以计算其大小以进行初始化,然后逐行分析每个数字。
您也可以将一个矩阵的所有工作放到一个函数中(并注意边界),并在您还有更多矩阵的情况下调用它。
由于您不想使用列表,并且一旦初始化就无法调整数组的大小,所以这并不容易。
有两种方法:读取文件并初始化数组,知道其大小(如@Maaddy发布)或“调整大小”数组。这是不可能的,但是如果您使用Arrays.copyOf()
,则可以创建一个新数组。
这个想法是创建一个“三维”数组,您可以在其中存储:矩阵,行和列;然后开始读取文件。 每次找到一个单词时,整个数组都会更新,从而创建一个长度增加一个新数组。
如果单词是“矩阵”,则多余的长度将添加到第一个位置(“存储”矩阵的位置)
如果单词是“ row”,那么将为当前矩阵添加空格。因此,以这种方式,当前矩阵将再有一个数组,用于存储列值。
如果单词为other,则为该列的值。调整列的大小并将其添加到正确的位置。
请注意,如果找到单词“ matrix”或“ row”,则新数组将初始化为没有长度的数组。这是因为稍后将在必要时调整大小。
代码如下:
//Initialize array with no positions
String[][][] arrays = new String[0][0][0];
Scanner sf = new Scanner(new File("path/matrices.txt"));
int matrix = -1;
int row = -1;
int column = -1;
while (sf.hasNext()){
String line = sf.nextLine();
if(line.equals("matrix")) {
//'Resize' array: Create new array with 1 more length and old data
arrays = Arrays.copyOf(arrays,arrays.length + 1);
//Start new matrix
arrays[++matrix] = new String[0][0];
row = -1;
column = -1;
}else if(line.equals("row")) {
//'Resize' matrix: Create a new array with 1 more length and old data
arrays[matrix] = Arrays.copyOf(arrays[matrix],arrays[matrix].length+1);
row++;
arrays[matrix][row] = new String[0];
column = -1;
}else{
//'Resize' matrix
column++;
arrays[matrix][row] = Arrays.copyOf(arrays[matrix][row],arrays[matrix][row].length+1);
arrays[matrix][row][column] = line;
}
}
sf.close();
//Print result
for(int i = 0 ; i < arrays.length; i++) {
System.out.println("Matrix "+i);
for(int j = 0; j < arrays[i].length; j++ ) {
for(int k = 0; k < arrays[i][j].length; k++) {
System.out.print(arrays[i][j][k]+ " ");
}
System.out.println();
}
System.out.println();
}
结果是:
Matrix 0
a b c
d e f
g h i
j k l
Matrix 1
m n o p q
r s t u v
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。