从邻接矩阵创建图

时间:2019-10-01 17:29:57

标签: java adjacency-matrix

在弄清楚如何向图中添加邻接矩阵文件时遇到麻烦。 即时通讯使用扫描仪和hasNextLine来遍历文件,但无法弄清楚如何将节点和边添加到我的图形中。任何帮助都是巨大的。

下面是一个文件示例,该文件从以下位置获取输入: here

这是我的图类:

public class Graph {

    ArrayList<Node> nodeList;
    ArrayList<Edge> edgeList;

    public Graph() {
        nodeList = new ArrayList<Node>();
        edgeList = new ArrayList<Edge>();
    }

    public ArrayList<Node> getNodeList() {
        return nodeList;
    }

    public ArrayList<Edge> getEdgeList() {
        return edgeList;
    }

    public void addNode(Node n) {
        nodeList.add(n);
    }

    public void addEdge(Edge e) {
        edgeList.add(e);
    }

    public String toString() {
        String s = "Graph g.\n";
        if (nodeList.size() > 0) {
            for (Node n : nodeList) {
                // Print node info
                String t = "\nNode " + n.getName() + ", abbrev " + n.getAbbrev() + ", value " + n.getVal() + "\n";
                s = s.concat(t);
            }
            s = s.concat("\n");
        }

        return s;
    }

}

这是我要从中添加矩阵的类。


public class DelivB {

    File inputFile;
    File outputFile;
    PrintWriter output;
    Graph g;

    public DelivB(File in, Graph gr) {
        inputFile = in;
        g = gr;

        // Get output file name.
        String inputFileName = inputFile.toString();
        String baseFileName = inputFileName.substring(0, inputFileName.length() - 4); // Strip off ".txt"
        String outputFileName = baseFileName.concat("_out.txt");
        outputFile = new File(outputFileName);
        if (outputFile.exists()) { // For retests
            outputFile.delete();
        }

        try {
            output = new PrintWriter(outputFile);
        } catch (Exception x) {
            System.err.format("Exception: %s%n", x);
            System.exit(0);
        }
        System.out.println("DelivB:  To be implemented");

        // --------------------------------Deliverable B
        // -------------------------------------------//
        try {
            Scanner scanner = new Scanner(new File(inputFileName));
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());

            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

0 个答案:

没有答案
相关问题