java—将网络表示形式作为数组存储到邻接矩阵中

qlvxas9a  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(291)

[javaa]如何将这个数组(输出)存储到邻接矩阵中?我从文件中读取,我的目标是将网络表示转化为邻接矩阵。
我真正想要的和我期望的结果:

1  3  163
1  6  321
1  11 274
...

我的代码:

public class Arr{

        public static void main(String[] args){

            int[] data = readFiles("Polska.txt");
            System.out.println(Arrays.toString(data));
        }

        public static int[] readFiles(String file){

            try{

                File f = new File(file);

                Scanner s = new Scanner(f);
                int ctr = 0;

                while(s.hasNextInt()){
                    ctr++;
                    s.nextInt();
                }
                int[] arr = new int[ctr];

                Scanner s1 = new Scanner(f);

                for(int i = 0; i < arr.length; i++)
                    arr[i] = s1.nextInt();

                return arr;

            }catch(Exception e){
                return null;
            }
        }
    }

输出:

[1, 3, 163, 1, 6, 321 ...]

Perl斯卡.txt

wr98u20j

wr98u20j1#

在这里:

public static void main(String[] args){

        int[][] data = readFiles("path.txt");
        if(data == null){
            System.out.println("this is not valid adjacency matrix");
            return;
        }
        for(int i = 0; i < data.length; i++)
            System.out.println(Arrays.toString(data[i]));

    }

    public static int[][] readFiles(String file){

        try{

            File f = new File(file);

            Scanner s = new Scanner(f);
            int ctr = 0;

            while(s.hasNextInt()){
                ctr++;
                s.nextInt();
            }

            int edge = (int)Math.sqrt(ctr);

            if(edge * edge != ctr){
                return null; // you should probably make this an error message
            }

            int[][] arr = new int[edge][edge];

            Scanner s1 = new Scanner(f);

            for(int y = 0; y < edge; y++)
                for(int x = 0; x < edge; x++)
                    arr[y][x] = s1.nextInt();

            return arr;

        }catch(Exception e){
            return null;
        }
    }

平方根起作用。

相关问题