【问题标题】:Getting integer values to array from file从文件中获取整数值到数组
【发布时间】:2020-04-22 01:25:30
【问题描述】:

我试图通过分隔逗号从文件中获取整数值并将它们放入二维数组中。 文件是这样的;

0,7,9,0,0,14
7,0,10,15,0,0
9,10,0,11,0,2
0,15,11,0,6,0
0,0,0,6,0,9
14,0,2,0,9,0

所以我希望第一行在数组 [0][0 到 5] 中,其他行也相同,例如数组 [2][1] 必须为 10。但我无法弄清楚算法这里根本没有二维数组。

public static void main(String[] args) throws FileNotFoundException {
    BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
    Scanner sc = new Scanner(reader);
    int[][] array = new int[6][6];

    while(sc.hasNextLine()){
        String line = sc.nextLine();
        String[] str = line.split(",");

        for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 6; j++) {
                    array[i][j] = Integer.valueOf(str[i]);
                }
        }
    }
}

【问题讨论】:

    标签: java arrays filereader


    【解决方案1】:

    您正在遍历每一行的每个值。您的索引之一需要是线,另一个需要是线内的位置。您只需要一个for 循环;您应该在 while 循环中增加另一个索引。

    public static void main(String[] args) throws FileNotFoundException {
        BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
        Scanner sc = new Scanner(reader);
        int[][] array = new int[6][6];
        int i=0;
        while(sc.hasNextLine()){
            String line = sc.nextLine();
            String[] str = line.split(",");
            for (int j = 0; j < 6; j++) {
                array[i][j] = Integer.valueOf(str[j]);
            }
            i++;
        }
    }
    

    您还应该考虑,如果文件超过 6 行或超过 6 行,这将失败,因此这不是非常健壮的代码。完成读取文件后,最好填充不同的(动态)数据类型并转换为数组。至少,您应该检查自己没有超出预期的指数范围。

    【讨论】:

    • 文件中实际上是一个稳定的 81x81 矩阵,但我想在这里制作一个 6x6 矩阵的原型。您的代码有效并且二维数组保存了这些值,现在我必须使用它们来查找相邻路径之间的最短路径。我不明白你最后说了什么,因为我是编程新手,所以你分享的代码适用于我的项目,或者你能告诉我我必须使用更多的具体内容吗?
    • 代码将按原样工作,只是有限制。由于您在这里真正处理的是矩阵,因此固定索引可能确实有意义。要解决索引超出范围的问题,只需将其添加到条件中即可。例如,在您的 while 循环中,您可以执行 while(sc.hasNextLine()&amp;&amp;i&lt;6)。您的 for 循环中需要类似的条件。如果逗号分隔的值少于 6 个,str[j] 将抛出异常,因为j 不存在。至于其他数据类型,我在想ArrayList。既然你有固定值,原始数组就可以了。
    【解决方案2】:

    你可以这样做。关键是Java中没有真正的多维数组。只是可以容纳数组的单个 D 数组。

            // allocate the "2D" array but no need to specify the rows.
            int[][] array = new int[6][];
    
            // starting row number
            int rowNumber = 0;
    
            while(sc.hasNextLine()){
                String line = sc.nextLine();
                System.out.println(line);
                String[] str = line.split(",");
    
                // here is where your code differs
                // allocate a new row based on length of items just read
                int[] row = new int[str.length];
    
                // Now copy and convert to ints.
                for (int i = 0; i < str.length; i++) {
                    row[i] = Integer.parseInt(str[i]);
                }
                // Then just assign the row to the row number.
                // you can do this because a two dimentional array is just an
                // one dimenional array of another one dimensional array.
                array[rowNumber++] = row;
            }
            // print them out for verification.
            // get each row (from the array of rows)
            for (int[] row : array) {
                System.out.println(Arrays.toString(row));
            }
    

    那么做了什么就像下面这样;

    int [][] matrix = new int[2][];
    matrix[0] = new int[]{1,2,3,4};
    // rows can be different sizes.
    matrix[1] = new int[]{1,2,3,4,5,6,7};      
    
    for (int i = 0; i <2; i++) {
       int[] row  = matrix[i];
       for (int j = 0; j < row.length; j++) {
            System.out.print(row[j] + " " );
       }
       System.out.println(); // next line
    } 
    
    

    【讨论】:

      【解决方案3】:

      这是一种更现代的方法,使用 NIOStreams

      int[][] read2dArrayFromFile(String path) throws IOException {
          return Files.readAllLines(Paths.get(path))
                      .stream()
                      .map(line ->
                               Arrays.stream(
                                   line.split("\\D+")  // split by anything that's not a digit
                               ).mapToInt(Integer::parseInt).toArray()
                      ).toArray(int[][]::new);
      }
      

      【讨论】:

        猜你喜欢
        • 2015-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-31
        • 2011-06-24
        • 2020-09-09
        • 2020-04-28
        • 1970-01-01
        相关资源
        最近更新 更多