从文件中获取矩阵 Java
Get matrix from a file 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 个二维数组),格式为
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 等,这就是为什么这个问题不是 的重复,因为它使用 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...
}
这就是你想要的。不幸的是,使用 2D 数组执行此操作相当困难,因为一旦设置了数组的大小,就很难管理更改它。因此,使用 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这样的动态数据结构,这样做真的很麻烦。但是,尽管如此,这里有一个代码可以完成您的工作(考虑到您只有两个矩阵),而无需使用任何列表:
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++;
}
对于每个矩阵,我们执行相同的操作:
-我们首先遍历矩阵以计算其大小以便能够对其进行初始化,然后逐行解析每个数字。
您不妨将一个矩阵的所有工作放入一个函数中(并注意边界),只要您还有更多矩阵,就可以调用它。
由于您不想使用 List 并且数组一旦初始化就无法调整大小,这并不容易。
有两种方法:读取文件并初始化知道大小的数组(如@Maaddy 发布的那样)或 'resizing' 数组。这是不可能的,但如果你使用 Arrays.copyOf()
就可以创建一个新数组。
想法是创建一个 'tridimensional' 数组,您可以在其中存储:矩阵、行和列;然后开始读取文件。
每次你找到一个词,整个数组都会更新,创建一个长度增加一倍的新数组。
如果单词是'matrix',额外的长度将被添加到第一个位置('store' 矩阵的位置)
如果单词是'row',那么将为当前矩阵添加space。这样一来,当前矩阵就多了一个数组来存放列值。
如果该词是其他词,则为该列的值。该列已调整大小并添加到正确的位置。
请注意,如果找到单词 '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
我目前有一个格式为
的文本文件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 个二维数组),格式为
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 等,这就是为什么这个问题不是
我目前拥有的顶后:
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...
}
这就是你想要的。不幸的是,使用 2D 数组执行此操作相当困难,因为一旦设置了数组的大小,就很难管理更改它。因此,使用 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这样的动态数据结构,这样做真的很麻烦。但是,尽管如此,这里有一个代码可以完成您的工作(考虑到您只有两个矩阵),而无需使用任何列表:
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++;
}
对于每个矩阵,我们执行相同的操作:
-我们首先遍历矩阵以计算其大小以便能够对其进行初始化,然后逐行解析每个数字。
您不妨将一个矩阵的所有工作放入一个函数中(并注意边界),只要您还有更多矩阵,就可以调用它。
由于您不想使用 List 并且数组一旦初始化就无法调整大小,这并不容易。
有两种方法:读取文件并初始化知道大小的数组(如@Maaddy 发布的那样)或 'resizing' 数组。这是不可能的,但如果你使用 Arrays.copyOf()
就可以创建一个新数组。
想法是创建一个 'tridimensional' 数组,您可以在其中存储:矩阵、行和列;然后开始读取文件。 每次你找到一个词,整个数组都会更新,创建一个长度增加一倍的新数组。
如果单词是'matrix',额外的长度将被添加到第一个位置('store' 矩阵的位置)
如果单词是'row',那么将为当前矩阵添加space。这样一来,当前矩阵就多了一个数组来存放列值。
如果该词是其他词,则为该列的值。该列已调整大小并添加到正确的位置。
请注意,如果找到单词 '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