简体   繁体   English

从外部文件中读取二维数组

[英]Reading a 2d array from an external file

I know this has been asked before, but I'm still confused after reading other's posts.我知道以前有人问过这个问题,但是在阅读了其他人的帖子后我仍然感到困惑。 I'm trying to read a cost adjacency matrix from an external file and use it to populate my 2d array which I'll end up printing.我正在尝试从外部文件中读取成本邻接矩阵并使用它来填充我将最终打印的二维数组。 I'm able to read the information in the text file, but my matrix isn't filling in properly.我能够读取文本文件中的信息,但我的矩阵没有正确填写。 Right now it looks like this:现在它看起来像这样:

在此处输入图像描述

What I'm shooting for would look like this,我要拍摄的东西看起来像这样,

         New York Boston Atlanta St.Paul
New York        0    120     400      -1
Boston        120      0    1700     500
Atlanta       400   1700       0      -1
St.Paul        -1    500      -1       0

Here is my code so far:到目前为止,这是我的代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;

public class Lab12MU2 {

    public static void main(String[] args) {
        String fileName;
        FileReader myFileRead;
        String[][] matrix;
        boolean populated = false;
        Scanner scn = new Scanner(System.in);
        System.out.print("Enter the name of the file: ");
        fileName = scn.nextLine();
        try {
            myFileRead = new FileReader(fileName);
            BufferedReader buffRead;
            buffRead = new BufferedReader(myFileRead);
            Scanner input = new Scanner(new File(fileName));
            int dim = 5;
            matrix = new String[dim][dim];
            int i, j;
            for (i = 0; i < dim; ++i) {
                for (j = 0; j < dim - 1; ++j) {
                    if (input.hasNext()) {
                        matrix[i][j] = input.nextLine();
                    }
                }
            }
            for (i = 0; i < matrix.length; i++) {
                for (j = 0; j < matrix[0].length; j++) {
                    System.out.print(matrix[i][j] + "\t");
                }
                System.out.println();
            }
            populated = true;
            myFileRead.close();
        }
        catch (Exception ex) {
            System.out.println("ERROR: File not found");
        }
    }
}

Any help in fixing my matrix to look anything close to my desired result is appreciated.感谢您在修复我的矩阵以使其看起来接近我想要的结果的任何帮助。 Also, here's the text file: https://www.dropbox.com/s/owikpr2vqx31kjn/CAM.txt?dl=0另外,这是文本文件: https://www.dropbox.com/s/owikpr2vqx31kjn/CAM.txt?dl=0

New York, Boston, Atlanta, St. Paul 
0, 120, 400, -1
120, 0, 1700, 500 
400, 1700, 0, -1
-1, 500, -1, 0

Notes after the code.代码后的注释。

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Lab12MU2 {

    public static void main(String[] args) {
        Path path = Paths.get("CAM.txt");
        try (Stream<String> lines = Files.lines(path)) {
            List<String[]> list = lines.map(line -> line.split(", "))
                                       .collect(Collectors.toList());
            String[][] matrix = list.toArray(new String[][]{});
            boolean first = true;
            for (int col = 0; col < matrix[0].length; col++) {
                if (first) {
                    first = false;
                }
                else {
                    System.out.print(" ");
                }
                System.out.print(matrix[0][col]);
            }
            System.out.println();
            for (int row = 1; row < matrix.length; row++) {
                first = true;
                for (int col = 0; col < matrix[row].length; col++) {
                    if (first) {
                        first = false;
                    }
                    else {
                        System.out.print(" ");
                    }
                    System.out.printf("%" + matrix[0][col].length() + "s", matrix[row][col]);
                }
                System.out.println();
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Above code assumes that the file name is CAM.txt rather than getting the file name from the user.上面的代码假定文件名是CAM.txt ,而不是从用户那里获取文件名。 Note that, according to the above code, the file must be in the working directory.请注意,根据上面的代码,文件必须在工作目录中。

The code uses the stream API and try-with-resources .该代码使用stream APItry-with-resources

Refer to the documentation for method printf .请参阅方法printf文档

When I run the above code, using the file from your question, I get the following output:当我使用您问题中的文件运行上述代码时,我得到以下 output:

New York Boston Atlanta St. Paul
       0    120     400       -1
     120      0    1700      500
     400   1700       0       -1
      -1    500      -1        0

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

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