简体   繁体   English

将文件中的数据加载到2D数组中

[英]Loading data from a file into a 2D array

The file in question is formatted as such 相关文件的格式如下

1 1 1 1 1 1 1 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 0 0 0 0 0 0 1 
1 1 1 1 1 1 1 1 

And I need a way to parse it into an array like this 我需要一种将其解析为这样的数组的方法

    int[][] array = {{1, 1, 1, 1, 1, 1, 1, 1},
                     {1, 0, 0, 0, 0, 0, 0, 1},
                     {1, 0, 0, 0, 0, 0, 0, 1},
                     {1, 0, 0, 0, 0, 0, 0, 1},
                     {1, 0, 0, 0, 0, 0, 0, 1},
                     {1, 1, 1, 1, 1, 1, 1, 1}};

So far I have worked this much out 到目前为止,我已经做了很多工作

        BufferedReader reader = new BufferedReader(new FileReader(fc.getSelectedFile()));
        String line = null;
        int[][] myArray;
        while ((line = reader.readLine()) != null){
            myArray = new int[6][8];
            for(int y = 0; y < myArray.length; y++)
                for (int x = 0; x < myArray[y].length; x++){

                    myArray[y][x] = Integer.parseInt(line);
                    loadedArray[y][x] = myArray[y][x];
                }
        }

And it is throwing an Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1 1 1 1 1 1 1 1 " Me and 2D arrays never really got along... 而且它在线程“ AWT-EventQueue-0” java.lang.NumberFormatException中引发异常:对于输入字符串:“ 1 1 1 1 1 1 1 1 1” Me和2D数组从未真正相处...

行也从6开始并增加-这将导致索引超出范围错误,因为您将无法访问该值。

You seem to know the number of lines before you read the file. 在读取文件之前,您似乎已经知道行数。 Therefore there's no need to recreate the array every time you read the line. 因此,无需在每次读取该行时都重新创建数组。 Simply parse line by line and start the index with 0. 只需逐行解析并从0开始索引。

package test2.newpackage;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class NewMain {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("data/test.txt")); // replaced with my test file here
        String line;
        final int rows = 6; // row count never changes
        int[][] myArray = new int[rows][];
        int currentRow = 0;
        while ((line = reader.readLine()) != null && !line.isEmpty()) {
            // System.out.println(line); // write file content to System.out just to be sure it's the right file
            String[] nums = line.trim().split(" "); // remove spaces at both ends of string before splitting
            int[] intLine = new int[nums.length];
            myArray[currentRow++] = intLine;
            for (int col = 0; col < nums.length; col++) {
                int n = Integer.parseInt(nums[col]);
                intLine[col] = n;
            }
        }
        reader.close();
        System.out.println(Arrays.deepToString(myArray));
    }

}

However, if you don't know the number of rows in advance, use a List<int[]> , eg ArrayList<int[]> instead of int[][] . 但是,如果您事先不知道行数,请使用List<int[]> ,例如ArrayList<int[]>而不是int[][] You can still convert to an array after you finished parsing. 完成解析后,您仍然可以转换为数组。

Update: 更新:

Since you seem to have spaces at the end of each line, trim before splitting: 由于您似乎在每一行的末尾都有空格,因此请在分割之前进行trim

Change 更改

String[] nums = line.split(" ");

to

String[] nums = line.trim().split(" ");

Edit: 编辑:

Maybe your last line containing digits ends with a newline character. 也许最后一行包含数字的行以换行符结尾。 Just to make sure you don't read a 7th line that contains only a empty string, I added a check for empty lines. 为了确保您不会读到仅包含空字符串的第7行,我添加了对空行的检查。

Edit 2: 编辑2:

Since you still have a problem, I changed the code to exactly the code I used. 由于您仍然有问题,因此我将代码更改为恰好使用的代码。 (I hardcoded the file). (我对文件进行了硬编码)。

Since that really isn't a radical change to the previously posted code, I can only guess the source of the error: 由于这实际上不是对先前发布的代码的根本更改,因此我只能猜测错误的来源:

  • You didn't properly recompile and use really use an old version of the program or 您没有正确地重新编译并使用了真正使用的旧版本程序, 或者
  • The only digits in your input file are 1 s or 输入文件中的唯一数字是1 s
  • Your file choosing mechanism is erroneous and you actually get a different file than you think. 您的文件选择机制是错误的,实际上您得到的文件与您想象的不同。

You could check, if content of the file that is read is what you think it is by uncommenting the line printing in the outer loop. 您可以通过取消注释外部循环中的行打印来检查所读取文件的内容是否与您认为的相符。

I see a few problems: 我看到一些问题:

  1. You're getting IndexOutOfBounds because you increment rows when it's already the size of the array. 之所以得到IndexOutOfBounds是因为当rows的大小已经达到数组的大小时,便会增加rows

  2. You should count the number of lines in the file before creating the 2D array 在创建2D数组之前,您应该计算文件中的行数

     int rows = 0; while (reader.readLine() != null) rows++; 
  3. Have a separate counter for the current row 在当前行有一个单独的计数器

  4. You set myArray to a new matrix every iteration of the loop. 您可以在循环的每次迭代中将myArray设置为新矩阵。 Set it once and just add to it in the loop. 设置一次,然后将其添加到循环中。


int rows = 0, 
    cols = -1;
String line = null;

// Count number of rows and columns
while ((line = reader.readLine()) != null) {
    rows++;
    if(cols == -1) cols = line.split(" ").length(); // only set once
}

// Pretty sure you can't read lines anymore, so close and recreate reader
reader.close();
reader = new BufferedReader(new FileReader(fc.getSelectedFile()));

final int[][] myArray = new int[rows][cols];

// Iterate over every row
for(int row = 0; (line = reader.readLine()) != null; row++){
    String[] nums = line.split(" ");

    for (int col = 0; col < cols; col++) {
        myArray[row][col] = Integer.parseInt(nums[col]);            
    }
}

reader.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM