Java 从邻接矩阵创建图形
我搞不清楚如何将邻接矩阵文件添加到图形中。 我使用扫描仪和hasNextLine浏览文件,但不知道如何将节点和边添加到我的图形中。任何帮助都是巨大的 以下是我从中获取输入的文件示例: 这是我的图形类:Java 从邻接矩阵创建图形,java,adjacency-matrix,Java,Adjacency Matrix,我搞不清楚如何将邻接矩阵文件添加到图形中。 我使用扫描仪和hasNextLine浏览文件,但不知道如何将节点和边添加到我的图形中。任何帮助都是巨大的 以下是我从中获取输入的文件示例: 这是我的图形类: public class Graph { ArrayList<Node> nodeList; ArrayList<Edge> edgeList; public Graph() { nodeList = new ArrayList
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;
}
}
您需要解析输入文件的每一行。您应该首先使用
split()
将该行拆分为各个部分。然后,您需要确定这些部分的含义。您应该从代码中后退一步,仔细考虑最终结果需要是什么。图中的节点代表什么?边代表什么?如何从文件中获取每一行的数据?编写一个小样本邻接矩阵,并绘制期望从中生成的图形。您需要解析输入文件的每一行。您应该首先使用split()
将该行拆分为各个部分。然后,您需要确定这些部分的含义。您应该从代码中后退一步,仔细考虑最终结果需要是什么。图中的节点代表什么?边代表什么?如何从文件中获取这些数据?编写一个小样本邻接矩阵,并绘制期望从中生成的图形。
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();
}
}
}