从文件中获取矩阵 Java

huangapple go评论70阅读模式
英文:

Get matrix from a file Java

问题

以下是你想要的翻译内容:

Scanner sf = new Scanner(new File("C:\\textfiles\\matrices.txt"));
int maxIndex = -1;
String text[] = new String[10000]; // 为了安全起见,我添加了比实际需要更多的空间
while (sf.hasNext()){
    maxIndex++;
    text[maxIndex] = sf.nextLine();
}
sf.close();

int counter = 0;
int iCounter = 0; // 行
int jCounter = 0; // 列

int matrix1[][];
int matrix2[][];
while (counter < maxIndex){
    if (counter == 0) {
        // 还未编写...
    }
    // 还未编写...
}

如果你需要进一步的翻译,请提供具体的代码部分。

英文:

I currently have a text file in the format

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

I would like to convert this into two integer matrices (stored as 2 2D arrays), in the format

a b c

d e f

g h i

j k l

and

m n o p q

r s t u v

So far, I have created a Scanner object of the file and put each line in a text array:

Scanner sf = new Scanner(new File(&quot;C:\\textfiles\\matrices.txt&quot;));
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();

This way, the text file is now contained in a string array, where each line is a new element of the array. Right now, I would like to partition the array into two arrays with each array being the matrices. How should I continue? (note: I am a total beginner and desire answers that are simple (no arraylist, hashmap, etc., and that's why this question is not a duplicate of How to read two matrices from a txt file in java because it uses BufferedReader, and there are other potential duplicate questions, so I would like to clear this up)

What I currently have after the top:

int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column

int matrix1[][];
int matrix2[][];
while (counter &lt; maxIndex){
    if (counter = 0)
    {
        \\not yet written...
    }
    \\not yet written...
}

答案1

得分: 3

这段代码实现了你想要的功能。不幸的是,使用二维数组来做这个功能要困难得多,因为一旦你设置了数组的大小,很难管理它的变化。因此,使用 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 {
        Scanner sf = new Scanner(new File("matrices.txt"));

        List<List<List<String>>> matrices = new ArrayList<>();

        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);
            }
        }

        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 + " ");
                }
                System.out.println();
            }
            i++;
            System.out.println();
        }
    }

    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
英文:

This does what you want. Unfortunately doing this with 2D arrays is considerably harder since once you set the size of an array its difficult to manage changing it. Therefore using ArrayList is much easier.

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 = &quot;matrix&quot;;
    public static final String ROW = &quot;row&quot;;

    public static void main(String[] args) throws FileNotFoundException {
        // Use correct file name here
        Scanner sf = new Scanner(new File(&quot;matrices.txt&quot;));

        // This is a List of 2D Lists
        List&lt;List&lt;List&lt;String&gt;&gt;&gt; matrices = new ArrayList&lt;&gt;();

        // easier to process lines as we&#39;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&lt;List&lt;String&gt;&gt; matrix = new ArrayList&lt;&gt;();
                    matrices.add(matrix);
                    hasBeenProcessed = true;
                    break;
                case ROW:
                    List&lt;List&lt;String&gt;&gt; currentMatrix = getMatrixBeingProcessed(matrices);
                    currentMatrix.add(new ArrayList&lt;String&gt;());
                    hasBeenProcessed = true;
                    break;
            }
            if (!hasBeenProcessed) {
                List&lt;List&lt;String&gt;&gt; currentMatrix = getMatrixBeingProcessed(matrices);
                List&lt;String&gt; currentRow = getCurrentRow(currentMatrix);
                currentRow.add(inputValue);
            }
        }

        // Print out the results:
        int i = 1;
        for (List&lt;List&lt;String&gt;&gt; matrix : matrices) {
            System.out.println(&quot;Matrix &quot; + i);
            for (List&lt;String&gt; row : matrix) {
                for (String element : row) {
                    System.out.print(element + &quot; &quot;); // no newline until end of the row
                }
                System.out.println(); // new line
            }
            i++;
            System.out.println(); // new line
        }
    }

    private static List&lt;String&gt; getCurrentRow(List&lt;List&lt;String&gt;&gt; currentMatrix) {
        int lastRow = currentMatrix.size() - 1;
        return currentMatrix.get(lastRow);
    }

    private static List&lt;List&lt;String&gt;&gt; getMatrixBeingProcessed(List&lt;List&lt;List&lt;String&gt;&gt;&gt; matrices) {
        int lastMatrix = matrices.size() - 1;
        List&lt;List&lt;String&gt;&gt; currentMatrix = matrices.get(lastMatrix);
        return currentMatrix;
    }
}

Output:

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

答案2

得分: 3

如@Rob所说,如果没有动态数据结构,如ArrayList,执行此操作将非常繁琐。但是尽管如此,这里有一个完成你的任务的代码(假设你只有两个矩阵),而不使用任何List:

int counter = 0;
int iCounter = 0; // 行
int jCounter = 0; // 列
int matrix1[][];
int matrix2[][];
int rowSize = 0, numberOfRows = 0;
counter = 2;
while (!text
0
+
网站访问量
.equals("row") && !text
0
+
网站访问量
.equals("matrix")) { counter++; rowSize++; } // 现在我们有了行大小 numberOfRows = 1; while (!text
0
+
网站访问量
.equals("matrix")) { if (text
0
+
网站访问量
.equals("row")) numberOfRows++; counter++; } // 现在我们有了总行数 matrix1 = new int[numberOfRows][rowSize]; counter = 2; //从第一个矩阵开始 // 现在counter应该指向第一个矩阵的第一行 while (!text
0
+
网站访问量
.equals("matrix")) { jCounter = 0; while (!text
0
+
网站访问量
.equals("row") && !text
0
+
网站访问量
.equals("matrix")) { matrix1[iCounter][jCounter++] = Integer.parseInt(text
0
+
网站访问量
); // 假设你的输入是整数,否则可以更改 // 为相应的类型(例如Long,Double等) counter++; } iCounter++; if (!text
0
+
网站访问量
.equals("matrix")) counter++; } // 现在我们完成了第一个矩阵,counter指向 // 第二个矩阵的第一个“row”,因此我们再次执行相同的操作 rowSize = 0; numberOfRows = 0; int startOfSecondMatrix = counter + 2; //稍后保存这个值 counter += 2; // 使counter指向第一个数字 while (counter < text.length && !text
0
+
网站访问量
.equals("row")) { counter++; rowSize++; } numberOfRows = 1; while (counter < text.length) { if (text
0
+
网站访问量
.equals("row")) numberOfRows++; counter++; } matrix2 = new int[numberOfRows][rowSize]; counter = startOfSecondMatrix; iCounter = 0; while (counter < text.length) { jCounter = 0; while (counter < text.length && !text
0
+
网站访问量
.equals("row")) { matrix2[iCounter][jCounter++] = Integer.parseInt(text
0
+
网站访问量
); counter++; } iCounter++; counter++; }

对于每个矩阵,我们执行相同的操作:

  • 首先遍历矩阵以计算其大小,以便能够初始化它,然后逐行进行,解析每个数字。
    你也可以将一个矩阵的所有操作放入一个函数中(并处理边界情况),只要你还有更多的矩阵需要处理,就可以调用这个函数。
英文:

As @Rob said, it's really cumbersome to do this without dynamic data structures such as ArrayList's. But nevertheless, here's a code that does your job (considering you have only two matrices), without using any List's:

int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];
int rowSize = 0, numberOfRows = 0;
counter = 2;
while (!text
0
+
网站访问量
.equals(&quot;row&quot;) &amp;&amp; !text
0
+
网站访问量
.equals(&quot;matrix&quot;)) { counter++; rowSize++; } //now we have the row size numberOfRows = 1; while (!text
0
+
网站访问量
.equals(&quot;matrix&quot;)) { if (text
0
+
网站访问量
.equals(&quot;row&quot;)) 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
0
+
网站访问量
.equals(&quot;matrix&quot;)) { jCounter = 0; while (!text
0
+
网站访问量
.equals(&quot;row&quot;) &amp;&amp; !text
0
+
网站访问量
.equals(&quot;matrix&quot;)) { matrix1[iCounter][jCounter++] = Integer.parseInt(text
0
+
网站访问量
); //supposing your input is Integers, otherwise, you can change //it to the corresponding type (i.e. Long, Double, etc) counter++; } iCounter++; if (!text
0
+
网站访问量
.equals(&quot;matrix&quot;)) counter++; } //now we finished with the first matrix, and the counter points to //the first &quot;row&quot; 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 &lt; text.length &amp;&amp; !text
0
+
网站访问量
.equals(&quot;row&quot;)) { counter++; rowSize++; } numberOfRows = 1; while (counter &lt; text.length) { if (text
0
+
网站访问量
.equals(&quot;row&quot;)) numberOfRows++; counter++; } matrix2 = new int[numberOfRows][rowSize]; counter = startOfSecondMatrix; iCounter = 0; while (counter &lt; text.length) { jCounter = 0; while (counter &lt; text.length &amp;&amp; !text
0
+
网站访问量
.equals(&quot;row&quot;)) { matrix2[iCounter][jCounter++] = Integer.parseInt(text
0
+
网站访问量
); counter++; } iCounter++; counter++; }

For each matrix we perform the same operations:
-We first go through the matrix to count its size to be able to initialize it, after that, we go row by row, and parse each number.
You might as well put all the work for one matrix into a function (and take care of the bounds) and call it as long you still have more matrices.

答案3

得分: 0

因为您不想使用List,而数组一旦初始化后就无法调整大小,所以这并不容易。

有两种方法:读取文件并在知道大小的情况下初始化数组(如@Maaddy发布的内容),或者对数组进行“调整大小”。如果使用Arrays.copyOf(),那是可行的,这样您就可以创建一个新数组。

思路是创建一个“三维”数组,您可以在其中存储:矩阵、行和列;然后开始读取文件。
每次找到一个单词时,整个数组将被更新,创建一个新数组,长度增加1。

如果单词是“matrix”,额外的长度将添加到第一个位置(存储矩阵的位置)

如果单词是“row”,则会为当前矩阵添加空间。因此,以这种方式,当前矩阵将有一个多出的数组,用于存储列值。

如果单词是其他内容,那么它是列的值。将调整列的大小,并添加到正确的位置。

请注意,如果找到单词“matrix”或“row”,新数组将被初始化为没有长度。这是因为在需要时将稍后调整大小。

以下是代码:

// 初始化没有位置的数组
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")) {
        // '调整大小'数组:创建一个新数组,长度增加1,并保留旧数据
        arrays = Arrays.copyOf(arrays, arrays.length + 1);
        // 开始新矩阵
        arrays[++matrix] = new String[0][0];
        row = -1;
        column = -1;
    }else if(line.equals("row")) {
        // '调整大小'矩阵:创建一个新数组,长度增加1,并保留旧数据
        arrays[matrix] = Arrays.copyOf(arrays[matrix], arrays[matrix].length+1);
        row++;
        arrays[matrix][row] = new String[0];
        column = -1;
    }else{
        // '调整大小'矩阵
        column++;
        arrays[matrix][row] = Arrays.copyOf(arrays[matrix][row], arrays[matrix][row].length+1);
        arrays[matrix][row][column] = line;
    }
}
sf.close();

// 打印结果
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 
英文:

Since you don't want to use List and arrays can't be resized once initialized, this is not easy.

There are two ways: Read the file and initialize arrays knowing the size (as @Maaddy posted) or 'resizing' arrays. That's not possible but it is if you use Arrays.copyOf() so you can create a new array.

The idea is create a 'tridimensional' array where you can store: matrix, row and column; and then start to read the file.
Every time you find a word the entire array will be updated creating a new array with one length more.

If the word is 'matrix' the extra length will be added to the first position (the position who 'store' the matrix)

If the word is 'row' then the space will be added for the current matrix. So in this way, the current matrix will have one more array where store the column values.

If the word is other then is a value for the column. The column is resized and added to the correct position.

Note that if a word 'matrix' or 'row' is found, the new array is initialized with no length. This is because will be resized later, when is necessary.

The code is as follows:

//Initialize array with no positions
String[][][] arrays = new String[0][0][0];
Scanner sf = new Scanner(new File(&quot;path/matrices.txt&quot;));
int matrix = -1;
int row = -1;
int column = -1;
while (sf.hasNext()){
	String line = sf.nextLine();
	if(line.equals(&quot;matrix&quot;)) {
		//&#39;Resize&#39; 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(&quot;row&quot;)) {
		//&#39;Resize&#39; 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{
		//&#39;Resize&#39; 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 &lt; arrays.length; i++) {
	System.out.println(&quot;Matrix &quot;+i);
	for(int j = 0; j &lt; arrays[i].length; j++ ) {
		for(int k = 0; k &lt; arrays[i][j].length; k++) {
			System.out.print(arrays[i][j][k]+ &quot; &quot;);
		}
		System.out.println();
	}
	System.out.println();
}	

And the result is:

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 

huangapple
  • 本文由 发表于 2020年10月16日 16:22:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64385470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定