首页 > 解决方案 > 将txt文件读入邻接矩阵

问题描述

我正在寻找一个包含这种格式的矩阵的文本文件:

1 2 3 4
1 3 1 4
1 5 5 1
1 1 1 1

dsadadasdasdasdasdasd

我想阅读文本文件直到空白行并忽略下面的其余文本。

我目前有这个,但不确定我是否接近。任何帮助,将不胜感激。谢谢

matrix = new int[4][4];

        input = new Scanner(new BufferedReader(new FileReader("input.txt")));
        String tempLine = null;

        while ((tempLine = input.nextLine()) != null)
        {
            if(!tempLine.isEmpty())
            {
                //System.out.println(tempLine);
                for(int i = 0; i < 4; i++)
                {
                    String[] vals = tempLine.trim().split(" ");
                    for(int j=0; j < vals.length; j++)
                    {
                        matrix[i][j] = Integer.parseInt(vals[j]);
                    }
                }
            }
            else
            {
                break;
            }
        }

        input.close();

我当前得到的输出是一个 4 x 4 数组,其中包含每个条目的最后一行。

1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

标签: java

解决方案


推荐阅读